4

Code1:

# coding:utf-8

sum = 5

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

if __name__ == '__main__':
    add(7, 8)

When I run the code above, I got the following error:

ssspure:python ssspure$ python test.py
Traceback (most recent call last):
  File "test.py", line 11, in <module>
    add(7, 8)
  File "test.py", line 6, in add
    print sum
UnboundLocalError: local variable 'sum' referenced before assignment

Code2:

# coding:utf-8

sum = 5

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

if __name__ == '__main__':
    add(7, 8)

I can run code2 successfully.

I only moved the print sum below "sum = x + y" statement. Why did Code1 fail but Code2 runs successfully?

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
ssspure
  • 51
  • 1
  • 2
  • 4
  • # coding:utf-8 sum = 5 def add(x, y): sum = sum + x if __name__ == '__main__': add(7, 8) this code also get error – ssspure Apr 16 '16 at 02:46
  • Does this answer your question? [Don't understand why UnboundLocalError occurs](https://stackoverflow.com/questions/9264763/dont-understand-why-unboundlocalerror-occurs) – snakecharmerb Dec 30 '19 at 16:23

2 Answers2

5

For code1:

You didn't declare sum. The sum you defined outside of the add function has no impact to the sum in you add function.

You can just put sum=0 in your function and that will work.

In fact, you are doing so in your code2. You innitialized sum as x+y

Michael Gao
  • 126
  • 5
1

the issue is because the local and global variable are of same name . so the function will give preference to local variable first . since the local variable is not assigned it gives the error local variable is not assigned.

we can solve this issue by following ways: 1. use global keyword in the function 2. keep names different. 3. use function globals()

thanks

Mukesh Gupta
  • 101
  • 1
  • 1
  • 6