“variable”是本地和全局Python

2024-10-02 08:17:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我得到了一个错误的函数,它应该改变一个全局变量来保存一个计数器。这是一个游戏,在这种情况下,它将是“玩家健康”和“力量”。如何修复此错误?在

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? 谢谢


Tags: the函数yougameif错误strengthprint
3条回答
def orcCombat(playerHealth, playerDamage, strength):

不需要将全局变量作为参数传递给函数。尝试:

^{pr2}$

当您将变量'strength'或本例中的foo传递给函数时,该函数将创建局部作用域,其中foo引用在函数test1上下文中传递的变量。在

>>> foo = 1
>>> def test1(foo):
...   foo = foo + 1
...   return
...
>>> test1(foo)
>>> foo
1

正如你所看到的,“全局”foo没有改变。在第二个版本中,我们使用global关键字。在

^{pr2}$

{看看这个}

另一个选择是将变量foo传递给函数,当从函数返回时,只返回变量foo 以及使用元组的任何其他变量。在

发生错误的原因是函数的strength参数与全局变量{}之间的命名冲突。重命名函数参数或将其完全删除。在

相关问题 更多 >

    热门问题