Home / Questions / What is Local Variables in Python?
Explanatory Question

What is Local Variables in Python?

👁 250 Views
📘 Detailed Answer
🕒 Easy to Read
Read the answer carefully and go through the related questions on the right side to improve your understanding of this topic.

Answer with Explanation

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

Accessing local variable outside the scope

def foo():
    y = "local"


foo()
print(y)

Output

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 foo() or local scope.


Let's see an example on how a local variable is created in Python.

Create a Local Variable

Normally, we declare a variable inside the function to create a local variable.

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

foo()

Output

local