Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Global Variables inside a Nested Function in Python

I read this code (given below) and my understanding was that, if a variable is declared global inside a function and if it is modified then it's value will change permanently.

x = 15
def change(): 
    global x 
    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

But the code below shows a different output. How is it that the value of x does not change inside the print("After making change: ", x) and still remains 15

def add(): 
    x = 15
    
    def change(): 
        global x 
        x = 20
    print("Before making changes: ", x) 
    print("Making change") 
    change() 
    print("After making change: ", x) 

add() 
print("value of x",x) 

Output:

Before making changes:  15
Making change
After making change:  15
value of x 20
like image 941
Mihir Avatar asked Dec 30 '22 23:12

Mihir


1 Answers

In add, x is not a global variable; it's local to add. You either need to make it global as well, so that add and change are referring to the same variable

def add(): 
    global x
    x = 15
    
    def change(): 
        global x 
        x = 20
    print("Before making changes: ", x) 
    print("Making change") 
    change() 
    print("After making change: ", x) 

add() 
print("value of x",x)

or you need to declare x in change as nonlocal, rather than global.

def add(): 
    x = 15
    
    def change(): 
        nonlocal x 
        x = 20
    print("Before making changes: ", x) 
    print("Making change") 
    change() 
    print("After making change: ", x) 

add() 
print("value of x",x)
like image 112
chepner Avatar answered Jan 14 '23 14:01

chepner