1

I am a beginner python coder trying to develop a simple text adventure game for a project. Most of the bugs and issues are relatively easy to resolve, but I keep having this one error when I try to reference an outside variable and add to it inside of a function.

Here's the code (using Python 3.9.5):

money = 0

def addmoney(q):
    q = int(q)
    money = money + q
    print(f'Added {q} to Money: {money}')
    print(f'You now have {money} money')

addmoney(100)

I keep getting an UnboundLocalError that says;

local variable 'money' referenced before assignment

I don't really understand what it means because I'm pretty sure I'm telling the function to add a specific quantity of money to the variable, but apparently I'm referencing it before giving it an assignment. It's probably something really easy that I'm missing, so hopefully someone can answer quickly before my mind blows in frustration lol.

  • If you want to mutate the `money` variable in an outer scope, you need to say `global money` at the start of your function to indicate that the `money` you're modifying is the global variable and not a new local variable with the same name. Note that this gets confusing quick and is not a good pattern to follow as a general rule -- the standard way to handle this is by putting the state in an object. – Samwise Jun 28 '21 at 17:45

3 Answers3

2

You have to mark money as being a global variable first. Otherwise, the code generated for the function assumes money is a local variable (due to the assignment) throughout the entire scope, and so money is undefined when you try to add q to its value.

def addmoney(q):
    global money
    money = money + q
    ...
chepner
  • 497,756
  • 71
  • 530
  • 681
1

You have to understand method variables vs global variables. This works for me.

def addmoney(q):
    global money
    q = int(q)
    money = money + q
    print(f'Added {q} to Money: {money}')
    print(f'You now have {money} money')
addmoney(100)
Added 100 to Money: 100
You now have 100 money
Mohamed Ali
  • 702
  • 8
  • 29
-1

I actually thought myself a little bit of Python, here follows a proper answer.

money = 0
def addmoney(currentMoney, aditionalMoney):
    aditionalMoney = int(aditionalMoney)
    print(f'Added {aditionalMoney} to Money: {currentMoney}')
    return currentMoney + aditionalMoney

money = addmoney(money, 100)

print(f'You now have {money} money')
C. Hellmann
  • 556
  • 6
  • 13