Search code examples
pythonthonny

Why is the IF statement still executing after it code block falls into the ELSE code block?


Click here for Image of my Code

I'm coding a simple text based adventure game, as im still learning the basics of python. The console is returning an error on line 15. The else condition gets executed on line 14, but it looks like the program still tries to execute, code after line 14. It was my understanding that after an else statement as been executed no if statements within the codeblock would be executed?

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

step_1 = input("Would you like to go left or right?")

if step_1.lower() == "left":
    step_2 = input("Swim or wait?")  
    if step_2.lower() == "wait":
       step_3 = input("Which door Red, Yellow or Blue?")
    else:
        print("Attacked by a trout. GAME OVER!") 
    if step_3.lower() == "red":
        print("Burned by fire. Game Over.")
    elif step_3.lower() == "blue":
        print("Eaten by beasts. Game Over.")
    elif step_3.lower() == "yellow":
        print("You Win!")
    else:
        print("Game Over.")     
else:
    print("You have fell into a hole, Game Over!")

Solution

  • According to you code, step_3 is only available within the if block on line 11. To fix this you need to declare step_3 above the if blocks, and then assign a value to it in the if block on line 11