0

Why does python have the following behaviour?

a = 4
def f1(): # No error: Returns 5. Global a unchanged
    a = 5
    return a
def f2(): # No error. Returns value of global a
    return a
def f3(): # Error: a used before assignment
    a = a + 1
    return a
def f4(): # Error: a used before assignment
    b = a
    a = b + 1
    return a
def f5(): # No error. Returns value of global a
    b = a
    return b

It seems like that Python sometimes permit the use of a global variable a and sometimes doesn't. What rule guides this?

Henricus V.
  • 898
  • 1
  • 8
  • 29
  • In Python you can read from a global, but you cannot write to it without explicitly declaring it as global. In f1() it creates a local variable a. In f2() and f5() it reads from the global. To use a global variable in Python you need to add the statement `global a` at the top before the assignment `a=4`. Then in the functions say that you are using the global variable by adding the statement `global a` before trying to use `a`. – L. MacKenzie Feb 23 '18 at 01:30
  • Any time you assign to a variable anywhere in a function definition, that variable will be local unless you use the `global` keyword – juanpa.arrivillaga Feb 23 '18 at 01:36

0 Answers0