I am an amateur in learing programming in Python. Recently, I found a question on local variable for functions. Here is my sample code:
"""
Scenario-1:
"""
a=4
def g(x):
#global a
#a=a+2
print(a)
return x+a
when I type g(2)
in console (I am using Enthought Canopy), it returns:
4
6
----nothing wrong.
then I change the code to (delete "#"
before "a=a+2")
:
"""
Scenario-2:
"""
a=4
def g(x):
#global a
a=a+2
print(a)
return x+a
then re-run the code and type g(2)
, it shows:
*UnboundLocalError: local variable 'a' referenced before assignment*
My 1st question is: in Scenario-1, as I return x+a
, why there is no referenced before assignment error?
Additionally, I change the code to:
"""
Scenario-3:
"""
a=4
def g(x):
global a
a=a+2
print(a)
return x+a
then I re-run the code and type g(2)
, it returns:
6
8
----nothing wrong. BUT, when I type a and enter in console, it returns:
4
Here comes my 2nd question, on global variable:
as I declare a to be global in function g(x), why variable a did not change to 6=4+2 (according to a=a+2)? I thought when variable a is so-called "global", the value changing in function inside will lead to the changing outside of the function, which is in main(). Am I wrong?
Above are my two basic questions. Thank you very much!