Home > Mobile >  Getting error in nested if else statement
Getting error in nested if else statement

Time:08-17

When I use the variable inside an else statement and in the else statement I use anther if statement and when I run the code I get an error NameError

print ("Welcome to Treasure Island.") 

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

Road = input('You\'re at a crossroad. Where do you want to go? Type "left" or "right" \n')

Road_lower = Road.lower() 

if Road_lower == "right": 

  print("You fall into a hole. Game Over")
  
else:
    
Island = input('You \'ve come to a lake There is an island in the middle of the lake. Type "wait" to wait for a boat. Type "swim" to swim across.\n') 
    
lowe_Island = Island.lower() 
  
if Island == "swim":

 print("You get attacked by an angry trout. Game Over.")
# When I run this code I get an error 

CodePudding user response:

When you enter left, the variable Island is assigned the input value, but when you enter right, it is never assigned and the program still continues to run. Introducing exit() in the 'if right' part should exit the script before you get to use a variable that has not yet been assigned a value.

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

Road = input('''You're at a cross road. Where do you want to go? Type "left" or "right" \n''')
Road_lower = Road.lower()

if Road_lower == "right":
    print("You fall into a hole. Game Over")
    exit()
else:
    Island = input('''You're come to a lake There is an island in the middle of the lake. Type "wait" to wait for a boat. Type "swim" to swim across.\n''')
    lowe_Island = Island.lower()

if Island == "swim":
    print("You get attacked by an angry trout. Game Over.")

CodePudding user response:

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

Road = input("You're at a cross road. Where do you want to go? Type 'left' or 'right' \n")
Road_lower = Road.lower()

if Road_lower == "right":
    print("You fall into a hole. Game Over")
else:
    Island = input("You're come to a lake There is an island in the middle of the lake. Type 'wait' to wait for a boat. Type 'swim' to swim across.\n")

lowe_Island = Island.lower()
if Island == "swim":
    print("You get attacked by an angry trout. Game Over.")
  • Related