首页 > 解决方案 > Python 3.x 上的基本脚本中的无限循环

问题描述

我开始在 python 3.x 中编码,在我的第一个脚本中我做了一个循环,而用户输入除 'b' 或 'B' 以外的任何其他内容时,他都留在循环中,但实际上当我输入 'b' 或 'B' 我留在循环中,我不知道为什么。

对不起我的英语我是你知道的青蛙x)

此致

我尝试用 raw_input 纠正这个问题,但似乎 raw_input() 在 python 3.x 中没有定义。

    ipt2 = input ('tapez b pour quitter')

    while ipt2 != 'b' or ipt2 != 'B':
        print(get_random_quote(quotes))
        ipt2 = input ('tapez b pour quitter')
        print(ipt2)

当我键入 B 时,我会留在循环中,我认为我必须退出循环,不是吗?

最后一行在这里查看 ipt2 的值是多少。

标签: python-3.x

解决方案


问题是您正在检查,or但在这种情况下您需要使用and

ipt2 = input ('tapez b pour quitter')

while ipt2 != 'b' and ipt2 != 'B':
    print(get_random_quote(quotes))
    ipt2 = input ('tapez b pour quitter')
    print(ipt2)

逻辑如下:

第一个例子

ipt2 = A

使用该行while ipt2 != 'b' and ipt2 != 'B':,我们检查以下内容:

1) ipt2 不是 'b' (ipt2 是 A 所以正确或True)

2) ipt2 不是 'B' (ipt2 是 A 所以正确或True)

这两个条件都是True如此循环继续。

第二个例子

ipt2 = B

现在我们再次检查:

1) ipt2 不是 'b' (ipt2 是 B 所以正确或True)

2) ipt2 is not 'B' (ipt2 is B 所以不正确或False)

一个条件是True,另一个是False循环继续,因为我们正在检查条件 1 条件 2是否为真。如果ipt2是,'B'则 ipt2 不是'b',反之亦然,一个结果将始终为 True,并且循环将继续。


推荐阅读