2016-01-25 25 views
0

前引用了我是通過一個偶然的戰鬥計劃的一半,我想使用的功能,以縮短我的工作。但我得到了錯誤,UnboundLocalError:局部變量「電子醫療」分配

UnboundLocalError: local variable 'Ehealth' referenced before assignment 

這是到目前爲止我的代碼...

import random 
import sys 
import time 

print ("You encounter a wild boar.") 

time.sleep(1) 

Weapon = input("Do you use a 'Bow and Arrow' or a 'Sword'.") 

Ehealth = (100) 
health = (100) 
Ealive = (1) 
alive = (1) 

def attack(): 
    damage = (random.randrange(5,21)) 
    time.sleep(3) 

    print ("You attack the Boar for " + str(damage) + " attack points.") 
    time.sleep(3) 

    Ehealth = (Ehealth - damage) 

    print ("The Boars health is at " + str(Ehealth) + ".") 
    time.sleep(3) 

if Weapon == ("Bow and Arrow"): 
    Emiss = (20) #out of 40 
    miss = (15)  #out of 40 

    Espeed = (random.randrange(1,11)) 
    speed = (random.randrange(1,11)) 

    if Espeed > (speed): 
     print ("The Boar is faster than you so he attacks first.") 
     time.sleep(3) 

     print ("Your health is at " + str(health) + " and the Boars health is at " + str(Ehealth) + ".") 
     time.sleep(3) 

     while (alive == 1):  #1 = alive, 2 = dead 
      Emiss = (random.randrange(1,41)) 
      if Emiss < (20): 

       print ("The Boar missed.") 

       attack() 

       if Ehealth > (0): 
        alive = (1) 

        continue 

       else: 
        alive = (2) 
        print ("You Won!") 

        sys.exit() 



      Edamage = (random.randrange(5,16)) 

      print ("The Boar attacks you with " + str(Edamage) + " attack points.") 
      time.sleep(4) 

      health = (health - Edamage) 
      time.sleep(4) 

      print ("Your health is at " + str(health) + ".") 
      time.sleep(4) 

      if alive <= (0): 
       print ("You died...") 
       sys.exit() 

      attack() 

      if Ehealth > (0): 
       alive = (1) 

      else: 
       alive = (2) 
       print ("You Won!") 

       sys.exit() 

我在該行的錯誤上

Ehealth = (Ehealth - damage) 

任何幫助,將不勝感激。

回答

0

您嘗試使用位於函數外部的變量。在任何情況下,我會這樣做:

def attack(): 
    global Ehealth 
    damage = (random.randrange(5,21)) 
    time.sleep(3) 

    print ("You attack the Boar for " + str(damage) + " attack points.") 
    time.sleep(3) 

    Ehealth = (Ehealth - damage) 

    print ("The Boars health is at " + str(Ehealth) + ".") 
    time.sleep(3) 

請注意,如果您要更改變量的值,則需要'global'關鍵字。

0

您指定給該變量在attack()功能:

Ehealth = (Ehealth - damage) 

分配的功能使得一個名字本地;你似乎希望它是一個全球性的,而不是。因爲它是一個地方,並在該行之前的功能尚未分配給,你得到你的錯誤。

告訴Python把它作爲一個全球性的,而不是。該行添加到您的函數(第一行可能是一個好主意):

global Ehealth 

這告訴了Python編譯器將函數內把Ehealth作爲一個全球性的,即使你分配給它。

0

EHEALTH是全局變量,如果你只是打印出來然後並且不會有任何錯誤但是當你試圖修改它,功能把它當作局部變量。 解決方案: -

def attack(Ehealth=Ehealth): 
相關問題