无法从 while 循环中跳出

Can't break out from while loop

我绝对是 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() 总是 returns 一个 str 并且您提供了一个 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' 现在正在做的事情。