[英]Having user input take string and int? (Python)
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. 问题是,要使代码运行年龄,必须将其转换为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? 但是,是否有一种方法可以使其运行而不必提示另一个问题?
I would suggest getting rid of the active
flag, and just break
ing 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: 我建议摆脱的active
标志,和刚刚break
荷兰国际集团时, "quit"
进入,像这样,那么你可以安全地转换为int
,因为如果代码将无法达到这一点"quit"
被输入:
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. 请注意, age >= 3
和age >= 12
支票是不必要的,因为您已经通过较早的支票保证了它们。
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. ")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.