Python Scope Of Variable 2

Local Variables

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

Example:

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

abc()

Output:

local

Example:

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

abc()
print(y)

When we run the code, the will output be:

NameError: name ‘y’ is not defined

The output shows an error, because we are trying to access a local variable y in a global scope whereas the local variable only works inside abc() or local scope.

Visitor Counter

0051011