错误;分配前引用的变量

时间:2012-09-26 05:35:31

标签: python

我为myhp获得Error; Variable Referenced Before Assignment。 在我的.py文件的开头,我有“myhp = 20”。

我该怎么做才能让它发挥作用?

def fightmode(name, hp, dmg, gold):
    print '\n\n\nYou are in a fight with %s' %name
    print '%s has %sHP' %(name, hp)
    while myhp > 0 and hp > 0:
        print '\n\t1. Attack \n\t2. Guard \n\t3. Run away.'
        opt1= ''
        allowed = ["1", "2", "3"]
        while opt1 not in allowed:
            opt1 = raw_input("\nWhat will you do? ")
            if opt1 == "1":
                hp = hp - mydmg
                print "You have inflicted %d damage on %s. %s's HP is %s" %(mydmg, name, name, hp)
            if opt1 == "2":
                myhp = myhp+5
                print "You are now guarding yourself. Your HP is now %d" %myhp

2 个答案:

答案 0 :(得分:2)

在函数的开头插入global myhp。如果在函数中赋值变量,Python会将其视为本地变量,除非您将其声明为全局变量。

答案 1 :(得分:0)

我看不到你的地方有myhp = 20. myhp是一个本地的,所以它还没有被分配。如果您想使用全局,请将global myhp放在函数的开头。