2012-09-26 25 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

您的診斷是正確的,但您的前提是錯誤的。 –

相關問題