Search code examples
pythonif-statementnameerror

Why do the if statements work, but NOT the else statements?


All if statements work, but the else statements in the first two if/else blocks return the following error? Can someone please tell me why this is?

Traceback (most recent call last):
  File "main.py", line 36, in <module>
    if swim_or_wait.lower() == "wait":
NameError: name 'swim_or_wait' is not defined

code

left_or_right = input("Choose which way you want to go. Left or right? ")

if left_or_right.lower() == "left":
  swim_or_wait = input("Do you want to swim or wait? ")
else:
    print("Wrong way. You fell into a hole. Game over.")

if swim_or_wait.lower() == "wait":
  which_door = input("Choose which door you want to go through? Red, blue, or yellow? ")
else:
  print("You've been attacked by a trout. Game Over.")

if which_door.lower() == "red":
  print("Burned by fire. Game Over.")
elif which_door.lower() == "blue":
  print("Eaten by beasts. Game Over.")
elif which_door.lower() == "yellow":
  print("Congratulations!!! The game is yours. You Win!")
else:
  print("Wrong door. Game Over.")`your text

Solution

  • swim_or_wait is only ever defined in the first if statement. If that first if statement doesn't trigger, then this variable does not exist. You essentially have a logic error as really you need to have this second if statement nested (ugh, there are better more elegant ways of doing this but this will suffice for a homework project that this sounds like).

    Forgive my formatting below on the indentations.

    Par Example:

    left_or_right = input("Choose which way you want to go. Left or right? ")
    
    if left_or_right.lower() == "left":
        swim_or_wait = input("Do you want to swim or wait? ")
        if swim_or_wait.lower() == "wait":
            which_door = input(
                "Choose which door you want to go through? Red, blue, or yellow?"
            )
            ## You'd be better with a case switch here
            if which_door.lower() == "red":
                print("Burned by fire. Game Over.")
            elif which_door.lower() == "blue":
                print("Eaten by beasts. Game Over.")
            elif which_door.lower() == "yellow":
                print("Congratulations!!! The game is yours. You Win!")
            else:
                print("Wrong door. Game Over.")
        else:
            print("You've been attacked by a trout. Game Over.")
    else:
        print("Wrong way. You fell into a hole. Game over.")