我得到了一个错误的函数,它应该改变一个全局变量来保存一个计数器。这是一个游戏,在这种情况下,它将是“玩家健康”和“力量”。如何修复此错误?在
strength = 1
playerHealth = 100
def orcCombat(playerHealth, playerDamage, strength):
orcHealth = 60
while orcHealth > 0:
if playerHealth > 10:
print "You swing your sword at the orc!, He loses", playerDamage, "health!"
playerHealth = playerHealth - 10
orcHealth = orcHealth - playerDamage
elif playerHealth == 10:
print "The Orc swings a deadly fist and kills you!"
print "Game Over"
else:
print "The Orc has killed you"
print "Game Over"
sys.exit()
if orcHealth <= 0:
print "You killed the Orc!"
print "+1 Strength"
global strength
strength = strength + 1
return "press enter to continue"
错误:**名称“strength”是全局和局部的。在
这是新密码。强度错误是固定的,但是全局变量playerHealth没有更改,如果我将playerHealth声明为一个全局变量,它将再次返回错误。在
^{pr2}$如何更改函数以更改全局变量playerHealth? 谢谢
不需要将全局变量作为参数传递给函数。尝试:
^{pr2}$当您将变量'strength'或本例中的
foo
传递给函数时,该函数将创建局部作用域,其中foo
引用在函数test1
上下文中传递的变量。在正如你所看到的,“全局”foo没有改变。在第二个版本中,我们使用
^{pr2}$global
关键字。在{看看这个}
另一个选择是将变量
foo
传递给函数,当从函数返回时,只返回变量foo
以及使用元组的任何其他变量。在发生错误的原因是函数的}之间的命名冲突。重命名函数参数或将其完全删除。在
strength
参数与全局变量{相关问题 更多 >
编程相关推荐