简体   繁体   中英

While loop with multiple conditions

So my while loop just keeps looping even when it shouldn't, if there is only 1 condition the loop works and then proceeds to the next lines of code but when I add the OR statement it wont work, I'm sure it's something very silly but I'm only a beginner and have tried researching this.

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()

The condition

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

will always be True . Any value of Choice will be either not "NEW GAME" or not "QUIT" . Instead, use:

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

I think you are looking for

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

or better to allow for alternative capitalization:

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

Also please uncapitalize the variable Choice . When other Python programmers see a variable that starts with a capital letter they assume at first that it is a class name.

I guess you want a and there, not a or

Because Choice can't be at the same time not different from "NEW GAME" and from "QUIT" . In other words, your loop condition is always True whatever the value of Choice is.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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