Wednesday, January 10, 2018

Global variables in Python

Global variables in Python behave a bit differently than in other programming languages. If we define a global variable outside a function and print it inside the function, everything works fine.
x = 5

def f():
    print("x = ", x)
f()
which results in
('x = ', 5)
However, if we include a second definition of the same variable within the function, the function loses its access to the global variable
x = 5

def f():
    x = 6
    print("x = ", x)
f()
print("but the global variable has not changed... => ", x)
which gives
('x = ', 6)
('but the global variable has not changed... => ', 5)
So if you define the same variable within the function, a new local variable is created, which is lost after the function finishes. The global variable is not affected.

However, if you try to modify the global variable within the function it will result in an error
x = 5

def f():
    x += 1
    print("x = ", x)
f()
which gives
UnboundLocalError: local variable 'x' referenced before assignment
I think this is very confusing. One has access to the global variable, as shown by the print statement, but can't modify it.

To actually modify the global variable we need the global keyword like this
x = 5

def f():
    global x
    x += 1
    print("x = ", x)
f()
which gives
('x = ', 6)
In other programming languages like C++ one would not be able to declare a variable within a function if a global variable with the same name already exists. Python does not require explicit variable declarations and therefore assumes that a variable that you assign has function scope, except if you explicitly state (using the global keyword) that you want to work with global variables. However, if you want to print or access a variable, Python is using the global variable if no local variable of that name exists.

Anyway, I hope that was helpful, if you have any questions/comments, please let me know in the comment section below.
cheers
Florian

No comments:

Post a Comment