0

我得到了一个Error; Variable Referenced Before Assignmentfor myhp。在我的 .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
4

2 回答 2

2

global myhp在函数开头插入。如果您在函数中分配变量,Python 会将其视为局部变量,除非您将其声明为全局变量。

于 2012-09-26T05:38:17.180 回答
0

我没有看到你在哪里有 myhp = 20。myhp 是这里的本地,所以它没有被分配。如果要使用全局,请将其放在global myhp函数的开头。

于 2012-09-26T05:36:51.120 回答