0
Why does two nearly identical statements show two different outcomes?
I am doing a course with while, and there is a question: You are making a ticketing system. The price of a single ticket is $100. For children under 3 years old, the ticket is free. Your program needs to take the ages of 5 passengers as input and output the total price for their tickets. and firstly i wrote: passenger = 0 total = 0 while passenger <= 5: age = int(input()) if age >= 3: total += 100 passenger += 1 print(total) and this gave me an EOF error while passenger = 0 total = 0 while passenger != 5: age = int(input()) if age >= 3: total += 100 passenger += 1 print(total) Was working. What is the problem with the first?
3 Respostas
+ 2
for first one, the loop will run 6 times, but you actually need 5 inputs for 5passenger
1st: passenger = 0, condition satisfies
2nd: passenger = 1, condition satisfies
3rd: passenger = 2, condition satisfies
4th: passenger = 3, condition satisfies
5tht: passenger = 4, condition satisfies
6th: passenger = 5, condition satisfies
7th: passenger = 6, condition doesn't satisfy, loop breaks
for 2nd one, works good,
1st: passenger = 0, condition satisfies
2nd: passenger = 1, condition satisfies
3rd: passenger = 2, condition satisfies
4th: passenger = 3, condition satisfies
5tht: passenger = 4, condition satisfies
6th: passenger = 6, condition doesn't satisfy, loop breaks....
so, if you had used "<5" in first code instead of "<=5" , it would have worked. Or else you could initialize passenger with "1" (passenger = 1), then it will work for first one
+ 4
In your second code, you say while passengers !=5, which means while passengers <5.
Your first code includes 5 as a parameter.
To a computer, nearly the same is not good enough.
It must be exactly as stated.
I wish people were like that. 😔
+ 3
In the first code, the while statement works 6 times. Cause passenger is 0 at initial and in the while, it says <= 5, so 0,1,2,3,4,5 you look it works 6 times. Also a solution, if you change passenger 0 to 1 at initially.
I hope, it's clear. Happy coding!