UnboundLocalError: local variable 'gold' referenced before assignment

Question:

Now before you decide to throw me out a window for not reading other questions, I’ve searched for this long and hard. I have in fact found many answers however they are in different context and I don’t really know how to use them with my code therefore I have concluded that it will be in my better interest, to instead of wasting time on other questions which will rather not give me the answer to my problem, asking about the exact error I am getting.

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()

Now, the error I get is to do with the “sell_function()“. When I run the program/game everything works up to until I type “sell” and enter. What I would want to happen is for the first item to be removed from the inventory, and depending on what type of item it is to add a certain amount of “gold“. However instead when I do that, it comes up with:

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

||

Answers:

Due to this line gold = gold+5 python thinks that gold is a local variable will not fetch the value of gold from the global variable gold when you actually call the function sell_function().

This happens because local variables in a function are decided when the function definition is parsed.

Use global statement if you want to modify a global variable:

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

Review function scope. Since you’re assigning a new value to gold, python creates a new variable. You then try increment it by 5, so it tries to take the value of the new ‘gold’, which throws the error.

UnboundLocalError: local variable 'gold' referenced before assignment

Declare ‘gold’ as a global variable in all functions that change it.

global gold
if inventory[0] in rawfish:
Answered By: maged
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.