Global keyword in the python example

Example 1: Accessing global Variable From Inside a Function

Python3




# global variable
a = 15
b = 10
 
# function to perform addition
def add():
    c = a + b
    print(c)
 
 
# calling a function
add()


Output:

25

If we need to assign a new value to a global variable, then we can do that by declaring the variable as global.

Example 2: Modifying Global Variable From Inside the Function

Python3




a = 15
 
 
# function to change a global value
def change():
    # increment value of a by 5
    b = a + 5
    a = b
    print(a)
 
 
change()


Output:

UnboundLocalError: local variable 'a' referenced before assignment

This output is an error because we are trying to assign a value to a variable in an outer scope. This can be done with the use of a global variable.

Example 3: Changing Global Variable From Inside a Function using global

Python3




x = 15
 
 
def change():
    # using a global keyword
    global x
 
    # increment value of a by 5
    x = x + 5
    print("Value of x inside a function :", x)
 
 
change()
print("Value of x outside a function :", x)


Output:

Value of x inside a function : 20
Value of x outside a function : 20

In the above example, we first define x as a global keyword inside the function change(). The value of x is then incremented by 5, i.e. x=x+5 and hence we get the output as 20. As we can see by changing the value inside the function change(), the change is also reflected in the value outside the global variable.

Global keyword in Python

In this article, we will cover the global keyword, the basic rules for global keywords in Python, the difference between the local, and global variables, and examples of global keywords in Python.

Similar Reads

What is the purpose of global keywords in python?

A global keyword is a keyword that allows a user to modify a variable outside the current scope. It is used to create global variables in Python from a non-global scope, i.e. inside a function. Global keyword is used inside a function only when we want to do assignments or when we want to change a variable. Global is not needed for printing and accessing....

Global keyword in the python example

Example 1: Accessing global Variable From Inside a Function...

Modifying global Mutable Objects

...

Global variables across Python modules

...

Global in Nested functions

...

Contact Us