0

So I'm currently learning to code in python and I wrote this basic text game. The idea is that you fight a boss and you have 66% chance of winning the fight, but if you lose (33% chance) you lose a life and if you have 0 lives you lose the game. The problem is with the lives variable. It's first set to 3 and the program is supposed to subtract 1 live from the player after each loss and do a sys.exit when lives variable is 0. However after the first loss the program crashes and gives this error:

Traceback (most recent call last):
  File "file path", line 24, in <module>
    boss()
  File "file path", line 21, in boss
    lives = lives - 1
UnboundLocalError: local variable 'lives' referenced before assignment

here is my code:

    import random, sys
    lives = 3
    #title screen
    print('SUPER NINJA WARRIORS PLANET')
    print('press A to start')
    menu = input()
    if menu == 'A' or 'a':
        pass
    else:
        print('press A to start')
    def boss():
        print('BOSS')
        print('press X to attack')
        attack = input()
        number = random.randint(1, 3)
        if number == 1:
            print('Boss defeated!')
        elif number == 2:
            print('Boss defeated!!')
        elif number == 3:
            print('Boss defeated You!')
            lives = lives - 1
    
    while True:
        boss()
        if lives == 0:
            sys.exit
        elif lives != 0:
            continue
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
capslock
  • 21
  • 2
  • 5

1 Answers1

1

According to Python documentation, if the compiler sees a variable assignment in a function/method (local scope), it will automatically mark that name as local and hence not consider any similarly named outside variables. That is why, when it sees that before assignment of the local variable it is used inside function for something else (to check a condition in your case), it will throw an error that you actually are trying to use a variable which has not been assigned yet (in local terms).

If you changed lives = lives - 1 to new_lives = lives - 1, then the compiler would treat lives as a global variable and not throw an Exception. But this would create more problems in your case. I suggest passing lives as an argument to the function - def boss(lives): and call it in your loop by passing lives boss(lives).