Search code examples
pythonscopeglobalvariable-assignmentlocal

Getting error when I try to print a global variable in a function in Python3


In this simple code to learn differences about global and local variable:

def sub():
    print(a)
    a="banana"
    print(a)

a="apple" 
sub()
print(a)

I am getting an error:

UnboundLocalError

Traceback (most recent call last) in
5
6 a="apple"
----> 7 sub()
8 print(a)

in sub()
1 def sub():
----> 2 print(a)
3 a="banana"
4 print(a)
5

UnboundLocalError: local variable 'a' referenced before assignment

I am currently understanding that 'a' is a global variable which is declared outside a function.

(It is not declared on any function like main() in C)

But why is this error telling me that 'a' is a local variable?

I know if I add global a above the print(a) line will solve this error, but I want to know WHY.


Solution

  • Python interprets this line: a="banana" in the function as the definition of a new, local, variable a. This variable in the scope of the function replaces the global variable a. Note that print(a) (reference to local variable a) occurs before a="banana" (= assignment). Hence you get the error: UnboundLocalError: local variable 'a' referenced before assignment.

    SEE ALSO:
    Why am I getting an UnboundLocalError when the variable has a value?
    Python gotchas
    The 10 Most Common Mistakes That Python Developers Make