我正在完成Eric Matthes的Python速成班的教科书作业
代码按照说明运行,但我想解决三个问题,但不知道如何解决。问题是:(1)我不知道我是否正确使用了该标志。(2) 我使用int()操作用户输入,以便将用户值与整数进行比较。(3) 如果用户输入'quit',程序将崩溃并显示错误(ValueError:int()的无效文本,以10为基数:“quit”)。这与我的第二期有关
谢谢你的帮助
大卫
-- 说明: 电影院根据人的年龄收取不同的票价。如果一个人未满3岁,车票是免费的;如果他们在3到12岁之间,票价是10美元;如果他们超过12岁,票价是15美元。写一个循环,询问用户的年龄,然后告诉他们电影票的价格
prompt = "\nI will price your ticket. What is your age?"
active = True #Per Matthes, using the flag Active, a program "should run while
#the flag is set to True and stop running when any of several events sets the
#value of the flag to False."
while active:
message = int(input (prompt))
if message < int(3):
print("Your ticket is free!")
elif int(3) <= message <= int(12):
print("Your ticket is $10!")
elif message > int(12):
print("Your ticket is $15!")
else:
active = False
break #Per Matthes, the break statement will force the program "to exit
#a while loop immediately without running any remaining code in the
#loop."
您可以尝试使用异常处理
如果这是你的问题,这将解决它
因此,评论也这么说,但以下是完整的解释:
要求用户输入年龄。无论您输入什么年龄,它都符合三个条件之一,因此输入的任何年龄都不会触发“else”条件
触发else的唯一方法是输入非整数,如单词或字母,但行
message = int(input (prompt))
尝试将输入转换为整数,因此输入任何其他内容都将引发异常您可以使用异常处理程序或通过实现执行退出响应的特定整数(如零)来解决此问题
下面是一个带有异常处理程序的示例:
这里有一个输入零将触发退出:
相关问题 更多 >
编程相关推荐