简体   繁体   中英

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.

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

The main reason is by placing

print(a)

inside a function sets variable 'a' as a local variable (ie, local scope) of that function. Ignoring the

a="apple"

defined outside the function.

And as 'a' value has not been initialized inside the 'sub' function hence its value couldn't be found while executing print(a) hence shows local variable 'a' referenced before assignment which is exactly what happens in the above case.

FOR SUMMARY

def sub():

#     print(a)  #Just comment this and you will understand the difference

## By doing print(a) inside sub function makes sets 'a' as local variable
## whose value has not been initialized
## and as its value couldn't be found while line print(a) executes hence shows
## local variable 'a' referenced before assignment which is exactly what 
##   happens

    a="banana" # a is assigned here 
    print(a)


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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM