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)
5UnboundLocalError: 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.