0

I am trying to make a hangman game, using 'or' in a while loop to check the input of the user. Without the 'or' the loop works fine, but when I add or with another condition, the output is always false.

def Guess():
guess = input("Type 'guess' to guess a character or 'answer' to guess the answer:\n>")
while guess != 'guess':
    guess = input("That is an invalid input. Please type 'guess' to guess a character or 'answer' to guess the answer:\n>")

This code works normally - if I input 'guess', the loop ends.

def Guess():
guess = input("Type 'guess' to guess a character or 'answer' to guess the answer:\n>")
while guess != 'guess' or guess != 'answer':
    guess = input("That is an invalid input. Please type 'guess' to guess a character or 'answer' to guess the answer:\n>")

When I add this, no matter what I input the loop will always keep running. Any ideas what is going wrong?

1 Answers1

2

guess is always unequal to at least one of these values, so you need and, not or:

while guess != 'guess' and guess != 'answer':

If you think that's confusing or hard to read, using De Morgan's law you can rewrite it as:

while not (guess == 'guess' or guess == 'answer'):

A shorter and more readable solution is to use not in:

while guess not in ['guess', 'answer']:
Thomas
  • 174,939
  • 50
  • 355
  • 478