Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Elif not executing in program

I am writing a simple text-based game for a college course in which I need to be able to move between rooms until the exit criteria are met. The problem I am running into is I can’t get the ELIF statement to work to set my location from the bedroom to the cellar. It keeps it as bedroom. I am not sure what I’m missing here.

rooms = {
    'Great Hall': {'South': 'Bedroom'},
    'Bedroom': {'North': 'Great Hall', 'East': 'Cellar'},
    'Cellar': {'West': 'Bedroom'}
}


location = 'Great Hall'
direction = ""


while direction != exit:
    print("\nYou are in the", location)

    possible_moves = rooms[location].keys()
    print("Possible moves:", *possible_moves)

    direction = input("Which direction do you wish to go? ").strip().capitalize()
    print("You entered:", direction)

    if direction in possible_moves:
        if location == 'Great Hall':
            location = 'Bedroom'

        if location == 'Bedroom':
            if direction == 'North':
                location = 'Great Hall'
            elif direction == 'East':
                location = 'Cellar'

        if location == 'Cellar':
            location = 'Bedroom'

    elif direction is not possible_moves:
        if direction == 'Exit':
            print("Thank you for playing the game.")
            break
        else:
            print('Invalid direction.')

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The issue is that when you change location from Bedroom to Cellar you straight away change it back again, if location == 'Cellar' matches, you need to change a couple of your ifs to elif

    if direction in possible_moves:
        if location == 'Great Hall':
            location = 'Bedroom'

        elif location == 'Bedroom': # if -> elif
            if direction == 'North':
                location = 'Great Hall'
            elif direction == 'East':
                location = 'Cellar'

        elif location == 'Cellar': # if -> elif
            location = 'Bedroom'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading