loops - 我可以在不使用“break”或不使用设置为“true”的变量的情况下退出循环吗
问题描述
我正在阅读一本书(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。使用设置为“真”的变量,即我们设置一个名为“活动”的变量并将其设置为“真”。活动时的外观:**
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 中缩进确实会影响编译过程,所以正确的缩进是根本
您将info_from_user 转换为 int,这是您在下面的 if 语句中进行比较所必需的。但是如果你将数据转换为int,那么显然你不能输入 quit,因为这显然不是一个整数。
我的建议是不要说一旦完成类型 'quit',而是说一旦完成类型 '-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$")
当然,还有更精细的选项可以做到这一点,也可以使用“退出”字符串,但就目前而言,我没有头脑想出一个不同的、更精致的解决方案。
推荐阅读
- javascript - 在日期选择器 js 中禁用时间
- amazon-web-services - CircleCI 部署到 AWS EC2
- javascript - 仅定位文本而不是嵌套元素
- r - 在 Windows 中的 R 中构建包
- css - 单击后的基础按钮
- python - Python - 读取 msgpack 文件并将其存储到数据框中
- javascript - ES6 .filter() 将返回一个没有特定字符串的对象数组
- angular - 如何使用 npm 安装 IONIC
- gitlab - GitLab 通知不起作用
- javascript - 允许从 highchart 工具提示输入文本(回写)