python-3.x - 无法从while循环中跳出
问题描述
我是 python 的绝对初学者,这是我遇到问题的代码。所以问题是当我按 0 时循环不会中断
while True:
idiot = input('Continue Y/N?: ')
idiot = idiot.upper()
if idiot == ('Y'):
print('Great')
if idiot == ('N'):
print('okey')
if idiot == 0:
print('exit')
break
解决方案
在你的情况下,True
永远不会改变False
哪个会结束循环。
将最后一个if
子句更改为if str(idiot) == '0'
可以解决问题,因为input()
始终返回 astr
并且您提供了int
(0 而不是 '0')。
while True:
idiot = input('Continue Y/N?: ')
idiot = idiot.upper()
if idiot == ('Y'):
print('Great')
if idiot == ('N'):
print('okey')
if idiot == '0':
print('exit')
break
无论如何,我总是将while
循环与包含布尔值(True / False)的变量一起使用。
使用该变量TrueOrFalse
,我可以将其设置为False
一旦满足条件。
这就是我会做的:
TrueOrFalse = True
while TrueOrFalse:
idiot = input('Continue Y/N?: ')
idiot = idiot.upper()
if idiot == ('Y'):
print('Great')
if idiot == ('N'):
print('okey')
if idiot == '0':
TrueOrFalse = False
print('exit')
还有一件事:我知道这只是一个例子,但你input()
只要求'Y'或'N'并且缺少'0'。无论如何,我猜'N'应该做(退出循环)'0'现在正在做的事情。
推荐阅读
- r - Shinyapp 的 MathJax 方程
- python - 使用 Joblib 将类对象实例作为输入参数的并行化函数
- node.js - xtermjs 如何从 webhook 或其他连接类型链接服务器和客户端
- docker - 从同一主机上的容器生成的请求中获取容器中的主机 IP
- list - 如何计算List数组的类别值
- dagster - 我可以在 map() 之后为多个实体使用一个 DynamicResource 的输出吗?
- vuejs2 - 从 gobal Vue 实例到应用程序的转换破坏了导入依赖
- merge - 合并 A 和 B 并保留所有差异
- web - 如何在 GCP 中构建具有内部 IP 限制的 Web 服务器
- javascript - 将字符串转换为具有重复键的对象到数组