Global Local and Nonlocal in python with example

In Python, there are three types of variable scopes: global, local, and nonlocal. The scope of a variable defines the region of a program where the variable is accessible.

  1. Global scope: A variable is defined in the global scope when it is declared outside of any function or class. The global variable can be accessed from anywhere within the program, including inside functions and classes.

Example:

x = 10  # global variable

def func():
    print(x)  # accessing global variable

func()  # output: 10

In the above example, the variable x is defined in the global scope and can be accessed from within the func() function.

  1. Local scope: A variable is defined in the local scope when it is declared inside a function or a loop. The local variable can only be accessed within the function or loop where it is defined.

Example:

def func():
    y = 20  # local variable
    print(y)  # accessing local variable

func()  # output: 20

In the above example, the variable y is defined in the local scope of the func() function and can only be accessed from within the function.

  1. Nonlocal scope: A variable is defined in the nonlocal scope when it is declared inside a nested function, and it refers to a variable in the enclosing function. The nonlocal variable can be accessed from within the nested function and the enclosing function.

Example:

def outer():
    z = 30  # variable in the outer function

    def inner():
        nonlocal z  # referencing the variable in the outer function
        z += 1  # modifying the variable in the outer function
        print(z)  # accessing the variable in the outer function

    inner()

outer()  # output: 31

In the above example, the variable z is defined in the nonlocal scope of the inner() function, which refers to the variable z in the enclosing outer() function. The variable z can be accessed and modified from within the inner() function, but it is not accessible from outside the outer() function.

Leave a Reply