0

I notice that global variables in Python (3.9.10) can be accessed within functions, but not mutated as shown below:

No error:

def absolute_value(number):
    print(y)
    if number < 0:
        return -number
    return number

y = 10
result = absolute_value(5)

Error:

def absolute_value(number):
    y = y + 2
    print(y)
    if number < 0:
        return -number
    return number

y = 10
result = absolute_value(5)

I would like to know the more general mechanism - which is, without using the global keyword, what's the most one can do with a global variable within a function's local namespace?

S.B
  • 13,077
  • 10
  • 22
  • 49
baubel
  • 87
  • 6
  • 1
    When you *"assign"* something to a variable, Python marks that variable as a "local variable". This happens at function's creation time. So in runtime, Python checks the local namespace for local variables. In the second example, in line `y = y + 2`, it tries to find `y` in local name space. What is `y` ? Nothing yet. So the right hand side of the assignment fails. – S.B Oct 05 '22 at 14:23
  • But if you don't assign to `y`(like in first example), it will find it in global namespace. It follows the LEGB rule. – S.B Oct 05 '22 at 14:24

0 Answers0