Python 赋值前引用的全局变量?
我是Python的新手,我正在尝试创建一个非常简单的代码,用户每次按enter键,就可以获得5分,然后打印出当前的分数。代码如下所示:Python 赋值前引用的全局变量?,python,python-3.x,pycharm,Python,Python 3.x,Pycharm,我是Python的新手,我正在尝试创建一个非常简单的代码,用户每次按enter键,就可以获得5分,然后打印出当前的分数。代码如下所示: pointsEarned = 0 alien_0 = {"points":5} new_points = alien_0["points"] def kill(): input("Press enter to kill an alien!") pointsEarned = pointsE
pointsEarned = 0
alien_0 = {"points":5}
new_points = alien_0["points"]
def kill():
input("Press enter to kill an alien!")
pointsEarned = pointsEarned + 5
killed()
def killed():
print("You just earned " + str(new_points) + " points!")
print("Current points: " + str(pointsEarned))
kill()
kill()
但是,当我运行此代码时,会出现以下错误:
UnboundLocalError: local variable 'pointsEarned' referenced before assignment
我不理解这一点,因为我事先在两个函数之外定义了pointsearn。如何解决此问题?将变量显式声明为
global
。如果变量位于赋值的左侧,则函数中的任何位置都会被视为局部变量,如果没有声明其他变量,则会被视为局部变量。
pointsEarned = 0
alien_0 = {"points":5}
new_points = alien_0["points"]
def kill():
global pointsEarned
input("Press enter to kill an alien!")
pointsEarned += 5
killed()
def killed():
print("You just earned " + str(new_points) + " points!")
print("Current points: " + str(pointsEarned))
kill()
kill()