电影票:电影院根据个人的年龄收取不同的票价。如果一个人未满3岁,则该机票是免费的;如果他们在3到12之间,门票是10美元;如果他们超过12岁,门票是15美元。写一个循环,在其中询问用户的年龄,然后告诉他们电影票的费用。
我希望这个程序具有戒烟价值。我可以使用0作为我的戒烟值,但我想使用'退出'。
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.")
答案 0 :(得分:6)
我想指出你不需要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)
替换,然后才能被读取。
答案 1 :(得分:2)
是的,如果你愿意,你可以嵌套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"
,代码就会循环播放。
答案 2 :(得分:1)
您可以使用try:
通过输入othert值而不是整数来避免脚本崩溃。
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 !!!'
pass