2012-09-26 31 views
0

我得到一个Error; Variable Referenced Before Assignment 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 
+0

我想你应该接受一个答案 – miracle173

回答

2

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

+0

我认为那样做了。但是现在我收到了这个错误。 “只能连接列表(不是int)到列表”my myp = myhp + 5 – user1692517

+0

nvm明白了:)非常感谢! – user1692517

0

我看不到你在哪里有myhp = 20。myhp是本地的,所以它没有被分配。如果您想使用全局功能,请在函数的开头放置global myhp

+0

这只是一个函数,我已经声明myhp在这个函数之外。 现在我想用它作为本地即时消息猜测 – user1692517

+0

您的诊断是正确的,但您的前提是错误的。 –

相关问题