问题描述
我正在阅读一本书(python 速成课程)并做练习。 我在代码中遇到问题,对于某些部分,我需要将变量集设置为字符串,然后将其更改为整数。
这是导致错误的尝试(我需要帮助):
prompt = " Tell me your age : "
prompt += "\n(Once finished type 'quit')"
#define variable and set to 'nothing' so python has something to compare
info_from_user = ""
# loop while the variable is not 'quit'
while info_from_user != 'quit':
info_from_user = input(prompt)
info_from_user = int(info_from_user)
if info_from_user < 3:
print("It's FREE for you")
elif info_from_user <= 12:
print("Please pay 10$")
elif info_from_user > 12:
print("Please pay 15$")
成功案例,仅供参考和充分理解:
**1。使用变量设置为“True”,即我们设置一个名为“active”的变量并将其设置为“True”。活动时的样子:**
prompt = "\n Tell me your age : "
prompt += "\n(Once finished type 'quit')"
#define variable and set in True
active = True
# apply loop that will be active as long as active is true using if/else
while active:
info_from_user = input(prompt)
# condition to stop the loop active if user inputs quit
if info_from_user == 'quit':
active = False
# else change variable to integer so python can compare user input with numbers.
else:
info_from_user = int(info_from_user)
if info_from_user < 3:
print("It's FREE for you")
elif info_from_user <= 12:
print("Please pay 10$")
elif info_from_user > 12:
print("Please pay 15$")
2.使用 break ,即当用户输入 'quit' 然后 break
prompt = "\n Tell me your age : "
prompt += "\n(Once finished type 'quit')"
#define empty variable so python got something to check against
info_from_user = ""
while info_from_user != 'quit':
info_from_user = input(prompt)
if info_from_user == 'quit':
break
else:
info_from_user = int(info_from_user)
if info_from_user < 3:
print("It's FREE for you")
elif info_from_user <= 12:
print("Please pay 10$")
elif info_from_user > 12:
print("Please pay 15$")
解决方法
不,如果没有某种流量控制,您将无法退出循环,您需要满足一些条件才能退出循环。第一个例子抛出错误的原因是
-
在第 4 行缩进不正确,在 python indentation does affect the compiling process 中,因此正确的缩进是基本的
-
您将 info_from_user 转换为 int,这是您在下面的 if 语句中进行比较所必需的。但是如果你将数据转换为int,那么显然你不能输入 退出,因为这显然不是一个整数。
我的建议不是说一旦完成输入'退出',而是说一旦完成输入'-1',这是一个标志值,您将用于让程序知道你想退出
prompt = " Tell me your age : "
prompt += "\n(Once finished type '-1')"
#define variable and set in True
info_from_user = 0
# apply loop that will be active as long as active is true using if/else
while info_from_user != -1:
info_from_user = input(prompt)
info_from_user = int(info_from_user)
if info_from_user > -1:
if info_from_user < 3:
print("It's FREE for you")
elif info_from_user <= 12:
print("Please pay 10$")
elif info_from_user > 12:
print("Please pay 15$")
当然还有更精细的选项可以做到这一点,也可以使用 'quit' 字符串,但至于现在,我没有脑子想出一个不同的、更完善的解决方案。