局部变量未分配,如果我稍后要在函数中更改它

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

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

如果我尝试修改 player_health:

,我会收到错误消息

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

当我可以在add函数中使用它时,怎么可能没有分配变量?它不承认它是一个 class 级别的变量,因为我试图在函数内部修改它吗? Python 是否必须将您要使用的每个 class 级变量传递给函数,以便它可以在本地范围内执行所有操作?

您需要输入 global player_health 才能在您在 player_health 中进行更改的每个函数中进行更改。