0

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!

3.1415926
  • 19
  • 3
  • Thank you for @sapam editing my texts and code! I must make it by myself next time – 3.1415926 Jul 01 '16 at 17:18
  • *Binding* determines the scope. Assignment is a form of binding; because you assign to `a` in `g()` it is determined to be a local. Other actions that bind are imports (using `import x` inside a function makes `x` a local), using a name as a target in `for`, or `except as name` or `with cm as name`, and more. – Martijn Pieters Jul 01 '16 at 17:20
  • Override the default by using the `global` statement. `global a` anywhere in `g()` will make `a` global again even though you bound to it. – Martijn Pieters Jul 01 '16 at 17:21
  • Last but not least, you have no `main()` in your function. `a` is a global, you assigned a new value to the global. – Martijn Pieters Jul 01 '16 at 17:23

1 Answers1

0

(1) You may reference a global variable without declaring it. However, Python requires the global declaration if you want to assign the value.

Prune
  • 76,765
  • 14
  • 60
  • 81