2

I have a variable a, and I want a to be added with b, like so:

a = a + b

Now, I have my program set up like so:

a = 2
b = 3

def add() :
    a = a + b
    print(str(a))

add()

Every time I run this, I get

Traceback (most recent call last):
File "<stdin>", line 8, in <module>
File "<stdin>", line 5, in add
UnboundLocalError: local variable 'a' referenced before assignment

instead of

5

Please explain the obvious mistake that I am making.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Metrojet64
  • 31
  • 1
  • 1
  • 4

2 Answers2

2

It's because of a thing called scope. You can read up about it, but essentially it means that inside a function, you may not have access to things defined on the outside.

To make the function aware of these variables, you need to pass them in. Try this:

a = 2
b = 3

def add(x, y) :
    x = x + y
    print(str(x))

add(a, b)

It's worth noting that these values are being passed into the function, but are actually not modified themselves. I won't go into the complexities surrounding the way variables are passed to functions, but suffice it to say that after you call add(a, b) here, the values of a and b will still be 2 and 3, respectively.

Thomas Kelley
  • 10,187
  • 1
  • 36
  • 43
  • 1
    I like this answer because it shows the OP how _not_ to use globals, instead of showing how _to_ use them. But it might be better to add a note at the end saying that when you really need to use globals you can, and how to do it. – abarnert Oct 31 '13 at 01:39
  • *You won't have access to things defined on the outside*. This is a little incorrect. In fact, you can access it, but you won't be able to modify it. – aIKid Oct 31 '13 at 02:21
  • Fair, and accurate. I've updated that line a little to "you may not have access to things defined on the outside". It's worth pointing out to the OP that the rules of "scope" vary from language to language. Python does allow you to read, but not change, a variable outside of a function's scope. – Thomas Kelley Oct 31 '13 at 16:54
0

I guess you are just learning about how to do this stuff, and you really don't want to go making everything global or you're going to get in a big mess.

Here, a and b are passed into the function. Inside the function, a and b are local variables and are distinct from the ones you declared outside the function

a = 2
b = 3

def add(a, b) :
    a = a + b
    print(str(a))
    return a

a = add(a, b)

The return a is so the function returns that local a so you can do something with it

John La Rooy
  • 295,403
  • 53
  • 369
  • 502