Explain Global, Local and Nonlocal variables.

Last updated 3 weeks, 5 days ago | 29 views 75     5

Tags:- Python

Python | Global, Local and Nonlocal variables

  • Global variables are public variables that are defined in the global scope.
  •  A variable declared inside the function's body or in the local scope is known as a local variable.
  • Nonlocal Variables are used in nested functions whose local scope is not defined. 
 

Global Variables:

A variable declared outside of the function or in global scope is known as a global variable. This means that a global variable can be accessed inside or outside of the function.

x = "global"
def fun():
    print("x inside:", x)

fun()

print("x outside:", x)

we use the global keyword to change the value of x inside the function


Local Variables

A variable declared inside the function's body or in the local scope is known as a local variable.

def fun():
    y = "local"
    print(y)


fun()

Nonlocal Variables:

Nonlocal variables are used in nested functions whose local scope is not defined. This means that the variable can be neither in the local nor the global scope. We use nonlocal keywords to create nonlocal variables.

def outer():
    x = "local"

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

inner()
print("outer:", x)

Note: If we change the value of a nonlocal variable, the changes appear in the local variable.