-1

For context, I'm making a simple number game and asking the user if they would like to play. If the user types "Yes" or "yes" the game should start if the user types "No" or "no" the game will end.

I started with an if/elif/else conditonal but my or operator isn't working so even if the user types "no" it continues the game and runs the next line of code. What am I doing wrong?

Here's my code:

`

if start_game == "Yes" or "yes" :
  print("Let's begin: ")
  print (random_number_one)
  input("Do you think the next number will be higher or lower? Type 'H' for higher or 'L' for lower:  ")
elif start_game == "No" or "no" :
  print("Okay, maybe next time.")
else:
  print("Invalid response. You lose.")

`

I'm not sure why it isn't running correctly and I'm not getting any errors. Is something else wrong?

1 Answers1

-1

Use the following code:

if start_game == "Yes" or start_game == "yes" :
  print("Let's begin: ")
  print (random_number_one)
  input("Do you think the next number will be higher or lower? Type 'H' for higher or 'L' for lower:  ")
elif start_game == "No" or start_game == "no" :
  print("Okay, maybe next time.")
else:
  print("Invalid response. You lose.")

Explanation

Python == operator has precedence over or operator so python sees your code as (start_game == "Yes") or ("yes") and (start_game == "No") or ("no").

A string like "yes" has a truthy value and so is interpreted as True.

So when input is "no", your 1st condition evaluate to (False) or (True) which is True.

More readable

if start_game in [ "Yes", "yes" ]:
  print("Let's begin: ")
  print (random_number_one)
  input("Do you think the next number will be higher or lower? Type 'H' for higher or 'L' for lower:  ")
elif start_game in [ "No", "no" ]:
  print("Okay, maybe next time.")
else:
  print("Invalid response. You lose.")

Note how you can use an array to check if a variable matches to one of multiple values.

AvirukBasak
  • 108
  • 3
  • 8