Global Keyword in Python Programming
Global Keyword in Python: Global keyword is the keyword used to change the current scope of variable ie. to convert the scope of a local variable to the global variable. We already know that global variable is accessible everywhere inside the program. But the local variable is only accessible inside the function only.
But what if we want to make the local variable of function to be the global variable. For that purpose, we use the “Global” keyword. That’s it nothing else.
Local and Global variable
You can easily differentiate between the local and global variable from the above given example. Here inside the fnc_name(), variable y is the local variable and it cannot be accessed outside of the function. If we want to access it outside we need to make it global first. For that purpose, we use the “Global” keyword.
Example elaborating the use of global keyword:
#Elaborating the use of Global Keyword x = "Global Variable" def fncn(): z = "local variable z" global y y = "local variable y" fncn() print(x) # X is global variable so it can be accessed anywhere print(y) # Y has been converted from local to global using "Global Keyword" #print(z) # Z is still local variable hence it generate error if we try to access outside of function
#Output #Global variable #local variable Y