【发布时间】:2020-05-20 14:01:05
【问题描述】:
我正在完成 Eric Matthes 的 Python Crash Course 教科书作业。
代码按照说明运行,但我想修复三个问题,不知道如何。问题是:(1)我不知道我是否正确使用了标志。 (2) 我使用 int() 来操作用户输入,以便我可以将用户值与整数进行比较。 (3) 如果用户输入'quit',程序将崩溃并显示错误(ValueError: invalid literal for int() with base 10: 'quit')。这与我的问题 2 有关。
感谢您的帮助!
大卫
-- 指示: 电影院根据一个人的年龄收取不同的票价。 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."
【问题讨论】:
-
1. active 标志和 break 语句本质上是做同样的工作——我会使用其中一个,但不会同时使用两者。它使读者更容易看到发生了什么。
-
2.使用
int()有什么问题?这里有什么问题? -
如果你想检查用户输入的不是数字的东西,你必须在之前应用
int()。而且写int(3)、3之类的东西已经没有意义了! -
3.您可能需要使用异常处理程序来处理此错误。