Today we’ll be talking about the global statement and global variables in Python.
This article is sort of complementary to my article on variable scopes, so you might want to read it first. Here’s the link. If you prefer to watch a video version, here it is:
Anyway, let’s start with the following example:
x = 10 # x in global scope
def func():
x = 5 # x redefined in local scope
print(x) # local x
func() # prints local x
print(x) # prints global x
If we have a global variable, like x, and assign a value to it in a function, then we’re not changing the value of the variable in global scope. Instead we’re creating a different object with the same name. From now on whenever we use the x variable inside the function, the local variable will be used, that’s why the func function prints 5 when called. But in global scope we still have the other variable, also x, but with the value of 10.
Here’s the output:
5
10
But we can easily use the same name in the function and work on the global variable in it. All we have to do is add the global statement. Let’s modify our code:
x = 10
def func():
global x
x = 5
print(x)
func()
print(x)
Now the output is:
5
5
So, when we use the global statement, we’re telling the program that we want to use the global variable instead of creating a new one. So, when we now assign a new value to x in the function, we’re actually assigning a new value to the global variable x. Hence the result.
What’s more, we can create global variables inside functions. Have a look at this:
def func():
global x
x = 5
print(x)
func()
print(x)
Now the global variable isn’t defined in global scope. It’s defined inside the function. Still, the global variable is created in global scope.
Now the output is:
5
5