[英]How to use a conditional test to exit a while loop?
First a little about the program itself: 首先介绍一下程序本身:
My problem is that I want the program to end if the user input is 'quit'. 我的问题是,如果用户输入为“ quit”,我希望程序结束。 The user input will besides 'quit' always be an int, because the program checks the users age. 用户输入除“ quit”外始终是一个int,因为该程序会检查用户的年龄。
This is my code: 这是我的代码:
prompt = "\nPlease enter your age to see the price for a ticket. \nEnter 'quit' when done: "
age = ""
while age != "quit":
age = input(prompt)
age = int(age)
if age < 3:
print("Your ticket is free.")
elif age > 3 and age < 12:
print("Ticket is $10")
else:
print("Ticket is $15")
This is the error i get when i put 'quit' as the input: 这是我输入“ quit”作为输入时遇到的错误:
Please enter your age to see the price for a ticket. Enter 'quit' when done: quit
Traceback (most recent call last): File "while_loops.py", line 60, in <module>
age = int(age) ValueError: invalid literal for int() with base 10: 'quit'
Many thanks in advance for your time and effort! 在此先感谢您的时间和精力! Best regards HWG. 最好的问候HWG。
Check for quit
before you try to convert to int
. 在尝试转换为int
之前,请检查quit
。 Run in an infinite loop and break out of it when you read the input quit
. 在无限循环中运行,并在读取输入quit
时中断它。
prompt = "\nPlease enter your age to see the price for a ticket. \nEnter 'quit' when done: "
while True:
age = input(prompt)
if age == "quit":
break
age = int(age)
if age < 3:
print("Your ticket is free.")
elif age > 3 and age < 12:
print("Ticket is $10")
else:
print("Ticket is $15")
Alternative which meet added criteria 符合附加标准的替代方案
not use 'break' or a variable as a flag 不要使用'break'或变量作为标志
Using an exception 使用异常
while ageStr != "quit":
ageStr = input(prompt)
try:
age = int(ageStr)
if age < 3:
print("Your ticket is free.")
elif age > 3 and age < 12:
print("Ticket is $10")
else:
print("Ticket is $15")
except ValueError:
pass
Using continue. 使用继续。
Note: this is bad as you specify and check for "quit" twice in the code and the control flow is overly complicated. 注意:这很不好,因为您在代码中指定并两次检查“退出”,并且控制流程过于复杂。
prompt = "\nPlease enter your age to see the price for a ticket. \nEnter 'quit' when done: "
age = ""
while age != "quit":
age = input(prompt)
if age == "quit":
continue
age = int(age)
if age < 3:
print("Your ticket is free.")
elif age > 3 and age < 12:
print("Ticket is $10")
else:
print("Ticket is $15")
while True:
age = input("\nPlease enter your age to see the price for a ticket. \n Enter 'quit' when done: '"
if age == 'quit':
break
# continue with the rest of your code
Just check to see if the input is 'quit', if so, break out of the infinite loop. 只需检查输入是否为“退出”,如果是,则跳出无限循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.