Need help with while loop and if statement

Hello I’m currently learning programming with python. I made a text adventure game where user can chose a path and if the path is correct go to next room else lost one life.
The problem is when the user chose first path correctly and filled in second path it started all over from the start
here is my code :

def play():
    life_remaining = 3
    print("Write n, e, s, w for north, east, south, west")
    message = "Where do you wants to go. You are in "
    while life_remaining > 0:
        get_input = input(message + "common room: ").casefold()
        if get_input == 'n':
            get_input = input(message + "bear room: ")
            if get_input == 'e':
                get_input = input(message + "grave: ")
                if get_input == 's':
                    get_input = input(message + "tunnel: ")
                    if get_input == 'e':
                        print("You won the game !!!")
                        break
                else:
                    life_remaining -= 1
                    print(f"You hit the wall and left {life_remaining} life")
            else:
                life_remaining -= 1
                print(f"You hit the wall and left {life_remaining} life")
        elif get_input == 's':
            get_input = input(message + "monster room: ")
        else:
            life_remaining -= 1
            print(f"You hit the wall and left {life_remaining} life")
    else:
        print("You lost the game")


play()

Could you write example which inputs result in errors, and what is expected instead?

@arkaruchiha
In my IDE the program works nicely. But some logical/commonsense confusions remain. What is your expected results ? only after knowing the expected results, we can reach in a logical conclusion. Seems that you have more than one common room ! ? Take paper and pencil and draw a sketch of the rooms. Then only you will get a good idea of the lay out of the rooms.

What I wants to get is if the user guess correctly in the first room go to the second room and if guess correctly again go to the third room else lost a life and return input from the second room. But with my code the user have to guess again from the start.Thanks

Ah, I though that was intended, so now it’s clear what is not working.

Notice what is happening is exactly what is in code - with each correct direction player get’s deeper and deeper into the if/else, when incorrect direction is chosen life is reduced and execution jumps out of the if/else statements, and ending up at the end of while block. That makes it loop back to the first room.

To go back to the previous - correct - room it’s needed to either keep track of that correct room, or in other way to keep player in the right place. There’s at least few different ways to do that.

2 Likes