UnboundLocalError: local variable 'gold' referenced before assignment

...

if chooseItem == "1":
                gold, arrows, whip, cannnonballs, heartPotions, megaHeartPotion, infinityPotion, infinityXPotion, duelBloodXXHealer, bloodXHeal, energyYPotion, basicRainbowHealer = bloodXHealerZZ.buy(gold, arrows, whip, cannnonballs, heartPotions, megaHeartPotion, infinityPotion, infinityXPotion, duelBloodXXHealer, bloodXHeal, energyYPotion, basicRainbowHealer)

Dani AI

Generated

A brief, practical explanation for future readers of this thread.

The UnboundLocalError for gold usually means a name is being treated as a local variable inside a function and is being read before it’s assigned. That is the scoping rule: if a function assigns to a name anywhere in its body, Python treats that name as local throughout the function. was right to point out that the name must have a value, while ’s suggestion to put the names in quotes is incorrect (strings are not the same as variables).

Minimal example that triggers the error:

gold = 100

def buy():            # Python sees the assignment below and makes `gold` local
    print(gold)       # UnboundLocalError: local variable 'gold' referenced before assignment
    gold += 10

Three common fixes:

# 1) Pass and return the value (preferred for pure functions)
def buy(gold):
    gold += 10
    return gold

# 2) Declare the global if a true global is intended
def buy():
    global gold
    gold += 10

# 3) Use an object to hold state (clean for game/player state)
class Player:
    def __init__(self): self.gold = 100
    def buy(self): self.gold += 10

Quick troubleshooting checklist: search the function for any assignment to gold (even in branches), confirm whether gold is meant to be local, global, or an attribute, and prefer passing/returning values or using an object for shared state. This explains the root cause behind the error mentioned by and clarifies the replies from and .

Recommended Answers

All 4 Replies

Can you be more precise? Please.

never mind I got it
thanks anyway!!

When you call
bloodXHealerZZ.buy(gold, arrows, whip, ...)
you need to have a value for gold, arrows, whip, and so on.

"gold", "arrows", "whip"

you forgot to put into double quotes.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.