Reputation: 49
In Python 3, we are currently learning how to use the 'while' function. The following problem was posed to us in the chapter about 'while' functions, so I would assume I need to use the 'while' function for the problem. However, I feel like I could solve the problem using 'if' statements rather than a 'while' statement. Can someone please tell me if I'm wrong?
"A movie theater charges different ticket prices depending on a person's age. If a person is under the age of 3, the ticket is free; if they are between 3 and 12, the ticket is $10; and if they are over age 12, the ticket is $15. Write a loop in which you ask users their age, and then tell them the cost of their movie ticket."
My code:
age = input("How old are you? ")
age = int(age)
if age < 3:
print("Your ticket is free.")
elif age > 3 and age < 12:
print("Your ticket is $10")
elif age > 12:
print("Your ticket is $15")
Will this solve the problem? Thanks!
Upvotes: 1
Views: 556
Reputation: 664
As pointed out already, your program should loop to allow many users to get the ticket price. Always make sure that you do not get stuck in an infinite loop, however, so you need to consider a way to escape the loop. I would suggest that the user can enter something like "Q" to quit.... however then you must consider: uppercase or lowercase... making the user input lowercase (only) for comparison takes care of this, so entering a "Q" will allow the loop to exit using the break statement.
Next, you should also consider that a user may enter "ten" for example, so to stop the float() "blowing up" and spitting an exception, using a try/except would handle this.
it is essentially "try to execute this code, and if it doesn't explode, continue" and except is like the "else" when using an if statement.
I hope this explains the need for a loop, but also other considerations when writing such programs, and how you might approach handling them.
while True:
age = input("\nHow old are you? (Q to quit)")
if age.lower() == "q":
break
try:
age = int(age)
if age <= 3:
print("Your ticket is free.")
elif age > 3 and age <= 12:
print("Your ticket is $10")
elif age > 12:
print("Your ticket is $15")
except:
print("Invalid entry")
print("\nGoodbye")
Upvotes: 1
Reputation: 11
'While' statement in this exercise is not for the 'age' variable but for the 'ask' process.
Upvotes: -1
Reputation: 27515
As per Leo stated, this is asking multiple users. Use:
age = None
while age is not "done": #or while True: for infinitely asking
#insert your code
This will keep asking for an age until "done"
is input
Upvotes: 0
Reputation: 2615
Write a loop in which you ask users their age, and then tell them the cost of their movie ticket
You have to ask multiple users their age in loop
Upvotes: 4