0
 prompt = "Enter your age for ticket price"
prompt += "\nEnter quit to exit: "
active = True
while active: 
 age = input(prompt)
 age = int(age)
 if age == 'quit':
 active = False
 elif age < 3:
 print("Your ticket is 5ドル")
 elif age >= 3 and age < 12:
 print("Your ticket is 10ドル")
 elif age >= 12:
 print("Your ticket is 15ドル") 

This is some fairly simple code but I am having one issue. The problem is, for the code to run age has to be converted into an int. However, the program is also supposed to exit when you type in "quit". You can always have another prompt along the lines of "Would you like to add more people?". However, is there a way to make it run without having to prompt another question?

asked Mar 1, 2019 at 18:36
1
  • 3
    check for "quit" first and break instead of using the active flag, then convert to int afterwards Commented Mar 1, 2019 at 18:37

2 Answers 2

1

I would suggest getting rid of the active flag, and just breaking when "quit" is entered, like so, then you can safely convert to int, because the code will not reach that point if "quit" was entered:

while True: 
 age = input(prompt)
 if age == "quit":
 break
 age = int(age)
 if age < 3:
 print("Your ticket is 5ドル")
 elif age < 12:
 print("Your ticket is 10ドル")
 else:
 print("Your ticket is 15ドル")

Note that the age >= 3 and age >= 12 checks are unnecessary, because you have already guaranteed them with the earlier checks.

answered Mar 1, 2019 at 18:40
Sign up to request clarification or add additional context in comments.

Comments

0

If you want to add another prompt, you can ask the first prompt before the loop and the other one at the end of it. And if you want to add the prices, you need a variable for it. If you dont want to prompt another question but want more user input, leave the prompt empty.

prompt = "Enter your age for ticket price"
prompt += "\nEnter 'quit' to exit: "
price = 0
user_input = input(prompt)
while True: 
 if user_input == 'quit':
 break
 age = int(user_input)
 if age < 3:
 price += 5
 elif age < 12:
 price += 10
 else:
 price += 15
 print(f"Your ticket is ${price}")
 user_input = input("You can add an age to add another ticket, or enter 'quit' to exit. ")
answered Mar 1, 2019 at 18:50

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.