Search code examples
pythonpycharm

How to update variable in if else statement with reference error


Working on a textbase game where you can move your character through rooms however, I keep running into an error about my position variable not being referenced

current_position = rooms[0]
def player_moves_south():
    if current_position == rooms[0]:
        current_position = rooms[1]
        print('welcome too the Bedroom you can now move North or East')
        player_choice = input()
        return player_choice

        return current_position
    else:
        print('error')

I keep getting an error saying

'current_position' not referenced

Can anyone help? It will be much appreciated


Solution

  • When I tried it like this.

    def player_moves_south():
         current_position = rooms[0]
         if current_position == rooms[0]:
            print('welcome too the Bedroom you can now move North or East')
            player_choice = input()
    
            return player_choice
    
            return current_position
    
         else:
             print('error')
    
    player_moves_south()
    

    It worked. I put the current_position in the function and it is giving me no error.

    If you want to use the current_position variable outside the function you can global it in the function. Like this

    global current_position
    current_position = rooms[0]