繁体   English   中英

打破循环的一种方法有效,而另一种方法无效

[英]One way of breaking out of a loop is working and the other way is not working

这段代码不起作用

    rsp = input("Please enter a command: ").strip()

    while rsp.lower() != "e" or rsp.lower() != "b":
        print("Invalid response, please try again!\n")
        rsp = input("Please enter a command: ").strip()

但是这个

    while True:
        rsp = input("Please enter a command: ").strip()

        if rsp.lower() == "e" or rsp.lower() == "b":
            break

        print("Invalid response, please try again.\n")

有人可以解释为什么第一个代码不起作用。 当我输入“ e”或“ b”时,我仍然停留在while循环中。

无论您输入什么,它都不是“ e”或“ b”,因此您的while语句始终为真。

尝试rsp.lower()!=“ e”和rsp.lower()!=“ b”。

这两个条件不相同:

rsp.lower() != "e" or rsp.lower() != "b":

与...不同

rsp.lower() == "e" or rsp.lower() == "b":

您可以通过以下方式使其更清晰:

rsp.lower() in ("e", "b"):

这还具有仅使用一次调用.lower()的额外好处。

问题在while循环的逻辑内:

while rsp.lower() != "e" or rsp.lower() != "b"

由于的or运营商,不管是什么类型字符为rsp.lower()它不会满足均为 “e”和为“B”并举。

那是,

if rsp.lower() == "e" :那么它不满足rsp.lower() == "b"

同样地:

if rsp.lower() == "b" :那么它不满足rsp.lower() == "e"

您要使用的是and运算符。 这将指示该字符既不是“ b”也不是“ e” 。:

while rsp.lower() != "e" and rsp.lower() != "b":

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM