Global in Nested functions

In order to use global inside a nested function, we have to declare a variable with a global keyword inside a nested function

Python3




# Python program showing a use of
# global in nested function
 
def add():
    x = 15
    def change():
        global x
        x = 20
    print("Before making changing: ", x)
    print("Making change")
    change()
    print("After making change: ", x)
 
add()
print("value of x", x)


Output:

Before making changing:  15
Making change
After making change:  15
value of x 20

In the above example Before and after making change(), the variable x takes the value of local variable i.e x = 15. Outside the add() function, the variable x will take the value defined in the change() function, i.e x = 20. Because we have used global keyword in x to create a global variable inside the change() function (local scope).



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