[英]Global variable declaration + Unbound Error: local variable referenced before assignment?
[英]Global variable referenced before assignment?
我是 Python 的新手,我正在尝试创建一个非常简单的代码,每次用户按下 Enter 键时,他们都会获得 5 分,然后是打印他们当前拥有多少分的行。 代码如下所示:
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
我不明白这一点,因为我事先在任一函数之外定义了 pointsEarned。 我该如何解决?
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.