Python global keyword is used to change the scope of variables. By default variables inside the function has local scope. Means you can’t use it outside the function.
Simple use global keyword to read and write a global variable inside a function.
Note: If a variable defines outside the funciton it is global by default. You don’t have to use
Example use of global keyword in Python
Simple example code declares a global variable inside a function and uses it outside the function. Here is how to create global variables from a no-global scope and print the value.
# Create a function: def my_func(): global var var = "My function variable" # Execute the function: my_func() # access global variable outside function print(var)
Without global keyword in variable
Let’s try the access a function variable outside the function scope.
def my_func(): var = "My function variable" my_func() # access variable outside function print(var)
Output: NameError: name ‘var’ is not defined
Global and Local Variable with the same name
It is possible to have a global and local variable with the same name.
# global variable s = "Global Variable" def func(): # local variable s = "Local Variable" print("I am a " + s) func() print("I am a " + s)
I am a Local Variable
I am a Global Variable
Do comment if you have any doubts and suggestions on this Python keywords tutorial.
Note: IDE: PyCharm 2021.1.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.