Global Variables in Python
In this tutorial, we will focus on this topic: Global Variables in Python. How to create and use those global variables let’s see.
Variables store data and are classified into two types
- Local Variables
- Global Variables
For instance, we are going to discuss Global Variables.
UNDERSTANDING GLOBAL VARIABLES
Global variables exist outside any function definition.
They allow users to modify variables inside the function definition.
Moreover, they can be accessed from anywhere in the program.
You may read this too: Scope of a variable, global and non-local keyword in Python
However, here is an example to understand what it is!
x = 12 # the scope of variable x here is global def func(): print (x) # using the global variable in the function func()
In other words, Certainly, what if the global and local variable’s name is identical!
x = 12 # the scope of variable x here is global def func(): x=3 # x is a local variable created here in this function func() print (x) # the local variable x is evaluated and prints 3 func()
Just now, The code overwrites the global variable name and starts performing with a local variable.
Above all, What if we want to use the global variable itself in any function!
How to create and use a Global Variable in Python
The global keyword creates Global Variables.
x = 12 # global variable def func(): global x # this line makes the use of global var "x" directly without creating any local variable. x = 1264 # changes global var "x" to 1264 from 12. print(x) func() print(x) # prints 1264 as in the function global x was used.
In conclusion, using a global keyword outside any function definition has no effect.
In addition, we are going to see the global variable in the Nested Function.
def outer(): # outer function x = 10 def inner(): # inner function global x # using global variable in nested function x = 50 print("Before calling inner function x: ", x) print("Calling inner function now") inner() print("After calling inner function x: ", x) outer() print("x in main function x : ", x)
* Global variables are most useful when multiple functions are accessing the same data.
x = 5 # global variable x def fun1(): print (x) def fun2(): print (x+4) def fun3(): print (x-4) fun1() fun2() fun3() # used global var "x" in multiple functions
Therefore, It is very clear that global variables help a lot in modifying variables and extend the facility of using variables in Python.