In this tutorial, we will learn what Python Global Keyword is, and where and when to use the same. So let us get started!
Python Global Keyword
Global Keyword
The global keyword in python helps to grab a variable from the global scope to the local scope and allows the function user-defined function to alter its values. With the help of the global keyword, we can create a global variable and alter it in a local scope that will reflect outside the local scope.
How to make a global variable using global keywords:
- if we use a global keyword inside the function it will grab that variable if it’s already defined or create a new variable.
- The changes made on the global variable will reflect outside the function too
Let’s understand it with some examples:
Example 1:
#Output
Example 2:
What if we create a local variable having the same name as a global variable?
#Output
Example 3:
What if we try to alter the value of global variable inside a function?
#Output:
Example 4:
Use a global keyword to grab the global variable and create a new global variable:
#Output
Global Variable Across the Python module
For now, think that Modules are the different python files containing python code. Now, create a module or create a new python file by name new.py and it should be on the same folder on which your main.py file. Now we will declare some variables in new.py file as global variables and then use a file change.py to change the values of new.py file and then call the new.py file variable in our main.py file and check whether the change.py file make changes in the new . py file variable or not
Let’s understand it with an example
#Output
Behind the code
In the above example, we created three files new.py, change.py, main.py. In new.py we declared two variables x and y then in change.py file we alter the values of new.py file variable x and y which we could see at our main.py file output . you can see that in our main.py file we import both new . py and change . py file if we only import new . py file so there would be no changes occur in the x and y values of the new.py file.
Global keyword in the nested loop
Let’s see how to make a global keyword acts inside a nested loop.
Example:
#Output
Behind the scene
In the above example, we can see that when we write global x inside the in_local() function it did not grab the local() function x variable instead it created a new global variable x has nothing to do with variable x of the local() function.