【问题标题】:One way of breaking out of a loop is working and the other way is not working打破循环的一种方法是有效的,另一种方法是无效的
【发布时间】:2019-07-13 09:21:16
【问题描述】:

这段代码不起作用

    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 循环中。

【问题讨论】:

  • 好好想想你的布尔条件的逻辑:) 你想要and 而不是or。 [换句话说,and 语句的逆语句是每个语句的否定之间的or。如果您有兴趣,请查阅德摩根定律]
  • 相关阅读:en.wikipedia.org/wiki/De_Morgan%27s_laws。练习:a or b 的反义词是什么? not a or not b的反义词是什么?

标签: python loops input while-loop


【解决方案1】:

无论你输入什么,它要么不是“e”,要么不是“b”,所以你的while语句总是正确的。

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

【讨论】:

    【解决方案2】:

    这两个条件不相同:

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

    不一样
    rsp.lower() == "e" or rsp.lower() == "b":
    

    你可以这样更清楚:

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

    这还有一个额外的好处,那就是只调用一次.lower()

    【讨论】:

      【解决方案3】:

      问题出在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":
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-02-04
        • 2012-08-30
        • 2011-05-12
        • 2012-03-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多