Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between non local variable and global variable?

I'm learning the concepts of programming languages.

I found the terminology "nonlocal" in python syntax.

What is the meaning of nonlocal in python?

like image 927
BAE HA RAM Avatar asked Sep 02 '25 18:09

BAE HA RAM


1 Answers

The nonlocal variables are present in a nested block. A keyword nonlocal is used and the value from the nearest enclosing block is taken. For example:

def outer():
    x = "local"
    
    def inner():
        nonlocal x
        x = "nonlocal"
        print("inner:", x)
    
    inner()
    print("outer:", x)

The output will be "nonlocal" both the times as the value of x has been changed by the inner function.

like image 85
Gunika Gupta Avatar answered Sep 04 '25 06:09

Gunika Gupta