【问题标题】:While loop with multiple conditions具有多个条件的while循环
【发布时间】:2015-05-05 01:38:16
【问题描述】:

所以我的 while 循环即使在不应该循环的情况下也会继续循环,如果只有 1 个条件循环工作,然后继续执行下一行代码,但是当我添加 OR 语句时它不会工作,我敢肯定这是非常愚蠢的事情,但我只是一个初学者并且已经尝试过研究这个。

Choice = input("What would you like to do? New Game, Continue, or Quit?").upper()
while Choice != "NEW GAME" or Choice != "QUIT":
    print ("That input was invalid, please try again.")
    Choice = input("What would you like to do? New Game, Continue, or Quit? ").upper()
    if Choice == "QUIT":
        quit()

【问题讨论】:

    标签: python


    【解决方案1】:

    条件

    Choice != "NEW GAME" or Choice != "QUIT"
    

    将永远是TrueChoice 的任何值都不是"NEW GAME" 或不是"QUIT"。相反,使用:

    Choice != "NEW GAME" and Choice != "QUIT":
    

    【讨论】:

    • 这很简单....我一直认为并且意味着这两个条件都必须为真,但那行得通,谢谢:)
    • 这正是and 的意思。但是这种情况下的条件是!=,而不是=
    【解决方案2】:

    我想你正在寻找

    while Choice not in ["New Game", "Continue", "Quit"]

    或更好地允许替代大写:

    while Choice.upper() not in ["NEW GAME", "CONTINUE", "QUIT"]

    还请取消大写变量Choice。当其他 Python 程序员看到一个以大写字母开头的变量时,他们首先假设它是一个类名。

    【讨论】:

      【解决方案3】:

      我猜你想要的是and,而不是or...

      因为Choice 不能同时不同于"NEW GAME""QUIT"。换句话说,无论Choice 的值是多少,您的循环条件始终为True

      【讨论】:

        猜你喜欢
        • 2017-05-03
        • 1970-01-01
        • 2013-09-29
        • 2013-08-07
        • 2015-02-14
        • 2013-06-30
        • 1970-01-01
        • 2011-01-09
        • 1970-01-01
        相关资源
        最近更新 更多