0
a = 17
 def test():
  print(a)
  a = 13
  print(a)
test()

This is an error message.

Traceback (most recent call last):
  File "sandbox.py", line 6, in <module>
    test()
  File "sandbox.py", line 3, in test
    print(a)
UnboundLocalError: local variable 'a' referenced before assignment

I expected this code will print out 17 13 but an error came out. First print(a) would print 17 because a=13 is not yet executed, and second print(a) would print local a which is 13 because variables are accessed from local to global.

what is wrong in my explanation? It seems I have some misunderstanding.. thanks

ben hwang
  • 1
  • 2
  • Welcome at Stack Overflow :) What did the error say that you received? – Amos Egel Sep 24 '18 at 11:27
  • Are you asking about the indentation error you (should) get? Or are you asking about unexpected output? Please elaborate on your problem, for example by showing us the expected and actual output. Also please read about [how to ask good questions](http://stackoverflow.com/help/how-to-ask), as well as [this question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/) – Some programmer dude Sep 24 '18 at 11:27
  • 3
    Your misunderstanding is not with print, but with the fact that any **assigment** to a variable name will make the variable **local** for the whole (function) scope, not just from the point of the assigment. Lookup the **global** keyword in the python docs. – Mike Scotty Sep 24 '18 at 11:27
  • Possible duplicate of [Assigning to variable from parent function: "Local variable referenced before assignment"](https://stackoverflow.com/questions/8934772/assigning-to-variable-from-parent-function-local-variable-referenced-before-as) – Thierry Lathuille Sep 24 '18 at 11:34

2 Answers2

2

Since your function defines a as a local variable, it is considered a local variable everywhere in the function. Your first print statement then references the variable before it's initially assigned.

Global variables can be confusing (and reasoning about what functions make changes to what globals is extra complicated) and best practice (in most languages) is to simply not use them. A better formulation of your sample might be

def test(a):
  print(a)
  a = 13
  print(a)

if __name__ == '__main__':
  test(17)
David Maze
  • 130,717
  • 29
  • 175
  • 215
0

You have to use global keyword before accessing the variable inside the function. For more reference see this link

a = 17
def test():
   global a
   print(a)
   a = 13
   print(a)
test()
Dschoni
  • 3,714
  • 6
  • 45
  • 80
Narendra Prasath
  • 1,501
  • 1
  • 10
  • 20