簡體   English   中英

“變量”是本地和全局Python

[英]'variable' is local and global Python

我在使用應該更改全局變量以保留計數器的函數時遇到了錯誤。 這是一款游戲,在本例中為“ playerHealth”和“ strength”。 如何解決此錯誤?

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聲明為全局變量,它將再次給我錯誤。

import sys

charisma = 1
strength = 1
intelligence = 1
agility = 1
courage = 1
playerDamage = 20
magic = 0
playerHealth = 100

def orcCombat(playerHealth, playerDamage):


    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"
        print "HP = ", playerHealth
        global strength 
        strength = strength + 1
    return "press enter to continue"

orcCombat(playerHealth, playerDamage)
print strength
print playerHealth

如何更改函數,以便更改全局變量playerHealth? 謝謝

def orcCombat(playerHealth, playerDamage, strength):

您無需將全局變量作為參數傳遞給函數。 嘗試:

def orcCombat(playerHealth, playerDamage):

當您將變量“ strength”或本例中的foo傳遞給函數時,該函數將創建局部范圍,其中foo引用在函數test1的上下文中傳遞的變量。

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

如您所見,“全局” foo沒有改變。 在第二個版本中,我們使用global關鍵字。

>>> def test2():
...   global foo
...   foo = foo + 1
...   return
...
>>> foo
1
>>> test2()
>>> foo
2

看看這個問題

另一種選擇是將變量foo傳遞給函數,當您從函數返回時,只需使用元組將變量foo以及其他變量一起返回即可。

由於函數的strength參數和全局變量strength之間的命名沖突而發生錯誤。 重命名功能參數或將其完全刪除。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM