Local variable is unassigned IF I'm going to change it later in the function

114 Views Asked by At
player_health = 10

def add(num):
  return num + player_health

def monster_room():
  print(player_health) # Error on this line
  player_health -= 1 # Doesn't crash without this line, even though the error is thrown on the previous line. 

print(add(6)) # works
monster_room() # doesn't work

See on Trinket

I get an error if I try to modify player_health:

UnboundLocalError: local variable 'player_health' referenced before assignment on line 10 in main.py

How the variable is possibly not assigned when I can use it in the add function just fine? Does it not recognize that it's a class-level variable because I'm attempting to modify it inside the function? Does Python have to pass every class-level variable you want to use to the functions so it can do everything at the local scope?

1

There are 1 best solutions below

0
On BEST ANSWER

You need to put global player_health to make changes in it in every function you make change in player_health.