2013-07-09 2 views
-3

다른 질문을 읽지 않기 위해 나를 밖으로 내 버리기로 결정하기 전에, 나는 오랫동안 열심히 찾았습니다. 나는 사실 여러 가지 대답을 찾았지만 서로 다른 맥락에있다. 그래서 나는 그것들을 내 코드와 함께 사용하는 방법을 정말로 모른다. 그러므로 나는 다른 질문에 시간을 낭비하는 대신에 더 나은 관심을 가질 것이라고 결론을 내렸다. 오히려 내 문제에 대한 답을주지 말고 내가받는 정확한 오류에 대해 묻는다.UnboundLocalError : 할당 전에 로컬 변수 'gold'가 참조되었습니다.

import time 
import random 
inventory = [] 
gold = 0 
rawfish = ["Mackarel", "Cod", "Salmon", "Herring", "Tuna"] 
trash = ["Old Shoe", "Thin Bone", "Rusted Empty Box", "Plank Fragment"] 
special = ["Copper Ring"] 

print" _   _  _  _  ______ _  _  _ "    
print" | |   | |  (_)  ()  | ____(_) | | (_)"    
print" | |  ___ | |_ __ _ _ __ |/ ___ | |__ _ ___| |__ _ _ __ __ _ " 
print" | | /_ \| | '_ \| | '_ \/__| | __| |/__| '_ \| | '_ \/_` |" 
print" | |___| (_) | | |_) | | | | | \__ \ | | | \__ \ | | | | | | | (_| |" 
print" |______\___/|_| .__/|_|_| |_| |___/ |_| |_|___/_| |_|_|_| |_|\__, |" 
print"    | |             __/ |" 
print"    |_|            |___/ " 
time.sleep(2) 
print".  .          /| /|  " 
print" \ /    o      |  |  " 
print" \ / .-. .--..--. . .-. .--.  o |  |  " 
print" \/ (.-' | `--. | ( )| |   |  |  " 
print" '  `--'' `--'-' `- `-' ' `-  o | o |  " 
time.sleep(2) 
print "In this current version the first item in your inventory is sold." 

def sell_function(): 
    if inventory[0] in rawfish: 
     sold = inventory.pop(0) 
     gold = gold+5 
     print "You have sold a", sold, "for 5 gold coins!" 
    elif inventory[0] in trash: 
     sold = inventory.pop(0) 
     gold = gold+5 
     print "You have recycled a", sold, "for 1 gold coins!" 
    elif inventory[0] in special: 
     sold = inventory.pop(0) 
     gold = gold+5 
     print "You have sold a", sold, "for 10 gold coins!" 
    else: 
     print "Shopkeeper:'You can't sell that.'" 

def fish_function(): 
    random_fishingchance = random.randrange(1,32) 
    if 1 <= random_fishingchance < 3: 
     inventory.append("Mackarel") 
     print "You have reeled in a Mackarel!" 
     time.sleep(0.5) 
     print "You place it into your inventory" 
    elif 3 <= random_fishingchance < 5: 
     inventory.append("Cod") 
     print "You have reeled in a Cod!" 
     time.sleep(0.5) 
     print "You place it into your inventory" 
    elif 5 <= random_fishingchance < 7: 
     inventory.append("Salmon") 
     print "You have reeled in a Salmon!" 
     time.sleep(0.5) 
     print "You place it into your inventory" 
    elif 7 <= random_fishingchance < 9: 
     inventory.append("Herring") 
     print "You have reeled in a Herring!" 
     time.sleep(0.5) 
     print "You place it into your inventory" 
    elif 9 <= random_fishingchance < 11: 
     inventory.append("Tuna") 
     print "You have reeled in a Tuna!" 
     time.sleep(0.5) 
     print "You place it into your inventory" 
    elif 11 <= random_fishingchance < 16: 
     inventory.append("Old Shoe") 
     print "You have reeled in an Old Shoe..." 
     time.sleep(0.5) 
     print "You place it into your inventory" 
    elif 16 <= random_fishingchance < 21: 
     inventory.append("Thin Bone") 
     print "You have reeled in a Thin Bone..." 
     time.sleep(0.5) 
     print "You place it into your inventory" 
    elif 21 <= random_fishingchance < 26: 
     inventory.append("Rusted Empty Box") 
     print "You have reeled in a Rusted Empty Box..." 
     time.sleep(0.5) 
     print "You place it into your inventory" 
    elif 26 <= random_fishingchance < 31: 
     inventory.append("Plank Fragment") 
     print "You have reeled in a Plank Fragment..." 
     time.sleep(0.5) 
     print "You place it into your inventory" 
    elif 31 <= random_fishingchance < 32: 
     inventory.append("Copper Ring") 
     print "You have reeled in a ring shaped object covered in mud." 
     print "After cleaning it you notice it is a Copper Ring!" 
     time.sleep(0.5) 
     print "You place it into your inventory" 
    else: 
     print "It seems your fishing line has snapped!" 


def action_function(): 
    while True: 
     action = raw_input("Do you want to 'sell' 'fish' 'inventory' 'money' or 'quit'?") 
     if action == "quit": 
      break 
      end 
     if action == "sell": 
      sell_function() 
     if action == "fish": 
      print "You throw your reel..." 
      time.sleep(10) 
      fish_function() 
     if action == "inventory": 
      print "You begin to open your inventory" 
      time.sleep(0.5) 
      print inventory 
     if action == "money": 
      print gold 
     if action == "gold": 
      print gold 
action_function() 

이제 오류는 "sell_function()"입니다. 내가 프로그램/게임을 실행할 때 "sell"을 입력하고 입력 할 때까지 모든 것이 작동합니다. 내가 원하는 것은 첫 번째 항목을 인벤토리에서 제거하고 어떤 유형의 항목에 따라 "gold"을 추가하는 것입니다. 내가 그렇게 할 때 대신, 함께 제공 :

Traceback (most recent call last): 
    File "C:\Users\Lolpin\Desktop\fishinglooptest.py", line 129, in <module> 
    action_function() 
    File "C:\Users\Lolpin\Desktop\fishinglooptest.py", line 116, in action_function 
    sell_function() 
    File "C:\Users\Lolpin\Desktop\fishinglooptest.py", line 43, in sell_function 
    gold = gold+5 
UnboundLocalError: local variable 'gold' referenced before assignment 
+1

여기에 심각한 인쇄가 있습니다. – arshajii

+0

... dict/list 적자의 심각한 징후 ... – tamasgal

답변

1

인해 gold = gold+5 파이썬 gold는 실제로 함수를 호출 할 때 지역 변수는 전역 변수 gold에서 gold의 값을 가져 오지 않을 것이라고 생각이 라인에 sell_function().

이는 함수 정의가 구문 분석 될 때 함수의 지역 변수가 결정되기 때문에 발생합니다.

def sell_function(): 
    global gold 
    if inventory[0] in rawfish: 
     sold = inventory.pop(0) 
     gold = gold+5 
+0

'global gold = gold + 5'라고 쓰면 "구문 오류"가 발생합니다 – Lolpin

+0

@Lolpin 대답의 코드를 읽었습니까? 전역 변수로 "gold"를 선언하는 * only *'global gold'를 포함하는 행을 가져야합니다. * 나중에 'gold = gold + 5'를하는 것은 예상대로 작동합니다. – Bakuriu

+0

@Lolpin은 함수의 맨 위에'global gold'를 추가 한 다음 정상적으로 금을 사용합니다. –

1

검토 기능 범위 :

사용 global 문 당신은 전역 변수를 수정하려면. gold에 새로운 값을 할당하기 때문에, python은 새로운 변수를 만듭니다. 그런 다음 5 씩 증가시켜 새로운 '금'값을 가져 오려고 시도합니다. 그러면 오류가 발생합니다.

UnboundLocalError: local variable 'gold' referenced before assignment 

변경하는 모든 기능에서 전역 변수로 '금'을 선언하십시오.

global gold 
if inventory[0] in rawfish: 
+0

감사합니다. 지금 이해합니다. D – Lolpin

관련 문제