Home > Enterprise >  Variable not defined error in a nested if/elif statement
Variable not defined error in a nested if/elif statement

Time:02-28

print("Welcome to Treasure Island.")
print("Your mission is to find the treasure.")

cross_road=input('You are at a crossroad. Where do you want to go? Type "left" or "right" ')
low_input = cross_road.lower()

if low_input == "right":
  print("You fell in a hole. Game Over.")
elif low_input == "left":
  swim_wait = input("swim or wait? ")
else:
  print("You fell in a hole. Game Over.")

low2 = swim_wait.lower()

if low2 == "swim":
  print("Attacked by trout. Game Over.")
elif low2 == "wait":
  doors = input("Which door? ")
else:
  print("Attacked by trout. Game Over.")

doors_low = doors.lower()

if doors_low == "blue":
  print("Eaten by beasts. Game Over.")
elif doors_low == "red":
  print("Burned by fire. Game Over.")
elif doors_low == "yellow":
  print("You Win!")
else:
  print("Game Over.")

I have a problem with this part:

elif low_input == "left":
  swim_wait = input("swim or wait? ")

I am not able to make the variable swim_wait! What I want is that if you answer "right" to the if, you lose, however elif they choose "left", they get the option to swim or wait. But I also have to save their response "swim" or "wait" in the variable swim_wait. But the error is that the variable is not defined.

CodePudding user response:

I think you forgot how if/else works.

cross_road=input('You are at a crossroad. Where do you want to go? Type "left" or "right" ')
low_input = cross_road.lower()

if low_input == "right":
  print("You fell in a hole. Game Over.")
elif low_input == "left":
  swim_wait = input("swim or wait? ")
else:
  print("You fell in a hole. Game Over.")

here if your user types right. you will print

"You fell in a hole. Game Over."

and you skip swim_wait. if your user initialy types left your code can accept swim_wait input. if you are trying to make a game based on user input you may need loops.

CodePudding user response:

This challenge is about understanding how logic flows through your program. Pranav has already given you a good tip to think about.

I can't give you the answer, as it's more beneficial for you to think it through at this stage of your learning, but I can offer two tips:

  1. Look up nested if statements and take time to understand how they work. If you use them, your program will work.

  2. The ".lower()" method can be placed at the end of your input functions like so: swim_wait = input("swim or wait? ").lower()

  • Related