Search code examples
pythonwhile-loopcountinfinite-loop

Why does variable containing "c" not equal "c" in my while loop? Trying to break when an input matches


I'm trying to implement a scoring system using counts that are initiated prior to this code. However, I want to keep checking the input until the user enters the correct winner. If they enter Adam, Bill or Draw the first time, the program skips my while loop. However, if they enter an option not here, like "Caroline", I get stuck in an endless loop in the while loop (even if I enter the correct answer once we enter the while loop).

Once I enter the while loop because of an initial failure, even if I type "adam", I receive the print error and I'm not sure why, since gameLower should == "adam". What am I missing?

game = input("Who won, Adam or Bill, or a draw (enter D for draw): ")
gameLower = game.lower()
print(gameLower)

while gameLower != "adam" or gameLower != "bill" or gameLower != "d":
    print("Sorry, I didn't understand who the winner was. Adam, Bill or a draw (D)?")
    game = input("Who won, Adam or Bill, or a draw (enter D for draw): ")
    gameLower = game.lower()
else:
    break

Solution

  • Your loop condition is a tautology, an expression whose truth value is always true regardless of its variables' values. You need to use and instead of or.

    gameLower value| != "adam" | != "bill" | != "d" | OR'ed | AND'ed
    ---------------+-----------+-----------+--------+-------+-------
    "adam"         |  false    | true      | true   | true  | false
    "bill"         |  true     | false     | true   | true  | false
    "d"            |  true     | true      | false  | true  | false
    "other value"  |  true     | true      | true   | true  | true