首页 > 解决方案 > 无法从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

标签: python-3.xwhile-loopbreak

解决方案


在你的情况下,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'现在正在做的事情。


推荐阅读