【问题标题】:if variable != "string" or variable != "string_2" always evaluates the same. Never goes to else [duplicate]if variable != "string" 或 variable != "string_2" 的计算结果总是相同的。永远不要去其他[重复]
【发布时间】:2020-08-30 22:47:39
【问题描述】:

我对下面代码的理解是,如果 user_input 不等于“up”或“down”,它应该一直循环。但如果它确实等于“向上”或“向下”,那么它会将 valid_move 更改为 True 并停止循环。但无论用户输入是什么,它总是打印(“无效条目”)并且永远不会退出 while 循环。

valid_move = False

while not valid_move:
    user_input = input("enter up or down")
        if user_input != "up" or user_input != "down"):
            print("invalid entry")

        else:
            valid_move = True
            print(user_input)

为什么会这样?

【问题讨论】:

  • or -> and .
  • if user_input not in ('up', 'down')

标签: python if-statement conditional-statements


【解决方案1】:

所述,在 if 语句中使用“and”而不是“or”

【讨论】:

    【解决方案2】:

    错误是你的条件,而不是:

    if user_input != "up" or user_input != "down")
    

    用途:

    if user_input != "up" and user_input != "down")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-02
      • 2020-03-10
      • 2023-04-05
      • 2013-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多