Python Global Keyword

In python, if you want to create a local variable inside the function and you want to access the same variable outside of the function as a global variable, then you need to define the variable with the global keyword.

 

Generally, if you create a variable inside of the function, that variable scope is limited to within that function but by using the global keyword, you can create global variables inside of the function.

 

Following is the example of creating the global variable inside of the function using the global keyword in python.

 

def greeting():
  global msg
  msg = "Learn Python"
greeting()
print("Welcome, "+ msg)

If you observe the above example, we created a global variable (msg) inside of the greeting() function using a global keyword, and we are accessing the same variable outside of the function.

 

When you execute the above python example, you will get the result as shown below.

 

Welcome, Learn Python

Change Global Variable Inside of Function

In some scenarios, we are not allowed to change the value of global variables inside of the function.

 

Following is the example of changing the global variable value inside of the function in python.

 

x = 10
def calculate():
    x = x + 2
    print("Inside x val: {}".format(x))
calculate()
print("Outside x val: {}".format(x))

When you execute the above python program, you will get the exception as shown below.

 

Traceback (most recent call last):
  File "variables.py", line 5, in calculate()
  File "variables.py", line 3, in calculate x = x + 2
UnboundLocalError: local variable 'x' referenced before assignment

In this case, the global keyword is useful to make changes to the global variables inside of the function.

 

Following is the example of changing the value of the global variable inside of a function using the global keyword in python.

 

x = 10
def calculate():
    global x
    x = x + 2
    print("Inside x val: {}".format(x))
calculate()
print("Outside x val: {}".format(x))

If you observe the above example, we are modifying the value of the global variable (msg) inside of the function by using the python global keyword.

 

When we execute the above program, we will get the result as shown below.

 

Inside x val: 12
Outside x val: 12

If you observe the above result, the global variable (msg) value has been updated with the changes we made in the calculate function.