Python Global, Local and Nonlocal variables

The scope of a variable plays an important role in any programming language. Variables in Python are categorized into three categories viz. global, local and non-local variables in Python programming.

What are the Python Global Variables?

The variables that are declared outside of functions are global variables. They can be accessed from anywhere of the program code, either inside or outside of a function. Let us take a look at an example to be more clear on how global variables are created and accessed.

x = 20


def my_func():
    print("Value inside function:", x)


my_func()
print("Value outside function:", x)
Value inside function: 20
Value outside function: 20

How to change Global Variable From Inside a Function?

Global variables can be accessed directly inside a function body, but it cannot be modified inside a function body. To do so, global keyword is used.

x = 20


def my_func():
    global x
    x = 10
    print("Value inside function:", x)


my_func()
print("Value outside function:", x)
Value inside function: 10
Value outside function: 10

What are the Python Local Variables?

A local variable is accessible inside a block of code like loop or functions and cannot be accessed outside the blocks.

def foo():
    y = 10
    print(y)

foo()

The above program print 10 in the screen. Here y is the local variable. We cannot access y outside of the function definition.

What are the Python Non-Local Variables?

The nonlocal variable is used in a nested function whose local scope is not defined. The nonlocal statement causes the listed identifiers to refer to previously bound variables in the nearest enclosing scope excluding globals. It takes the one “closest” to the point of reference in the source code. This is also called “Lexical Scoping”.

def outer():
    x = 10

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

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


outer()
The output of the above program is:-
inner: 20
outer: 20
SHARE Python Global, Local and Nonlocal variables

You may also like...

Leave a Reply

Your email address will not be published.

Share