电影票:电影院根据人的年龄收取不同的票价。如果一个人在3岁以下,门票是免费的;如果他在3岁到12岁之间,门票是10美元;如果他超过12岁,门票是15美元。写一个循环,你问用户他们的年龄,然后告诉他们电影票的价格。
我希望这个程序有退出的价值。我本可以使用0作为退出值,但我想使用' quit‘。
prompt = "What is your age? "
prompt += "\nEnter 'quit' to close program."
age = 0
while True:
age = raw_input(prompt)
if age == 'quit':
break
else:
age = int(age)
if age < 3:
print("The movie ticket is FREE for you.")
elif 3 <= age < 12:
print("The movie ticket is $10 for you.")
elif age >= 12:
print("The movie ticker is $15 for you.")发布于 2017-01-21 16:28:10
我想指出的是,您不需要else子句。您可以在先前的缩进级别包括其余的条件条件,因为break将退出循环,而不是继续循环主体的其余部分。
而不是
if age == 'quit':
break
else:
age = int(age)简单地说:
if age == 'quit':
break
age = int(age)如果不清楚这一点,这里是整个程序的变化:
prompt = "What is your age? "
prompt += "\nEnter 'quit' to close program."
while True:
age = raw_input(prompt)
if age == 'quit':
break
age = int(age)
if age < 3:
print("The movie ticket is FREE for you.")
elif 3 <= age < 12:
print("The movie ticket is $10 for you.")
elif age >= 12:
print("The movie ticker is $15 for you.")我还删除了无用的赋值:age = 0,因为在读取该值之前,该值已被age = raw_input(prompt)替换。
发布于 2017-01-21 16:56:17
是的,如果你喜欢,你可以嵌套if语句,但我总是尝试先找到一种更好的方法。在这种情况下,我们可以使用while语句的条件部分。
age = 0
while age != "quit":
age = raw_input(prompt)
age = int(age)
if age < 3:
print("The movie ticket is FREE for you.")
elif 3 <= age < 12:
print("The movie ticket is $10 for you.")
elif age >= 12:
print("The movie ticker is $15 for you.")现在,只要age不等于"quit",代码就会循环。
发布于 2017-01-21 17:21:07
您可以使用try:通过输入其他值而不是整数来避免脚本崩溃。
prompt = "What is your age? [quit to Exit the program] : "
while True:
age = raw_input(prompt)
if age == 'quit':
break
try:
age = int(age)
if age < 3:
print("The movie ticket is FREE for you.")
elif 3 <= age < 12:
print("The movie ticket is $10 for you.")
elif age >= 12:
print("The movie ticker is $15 for you.")
except:
print 'Invalid Age entered !!!'
passhttps://stackoverflow.com/questions/41777211
复制相似问题