What is Local Variables in Python?

Python >   Variable in Python >   Python Variables  

Long Question

251


Answer:

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


This Particular section is dedicated to Question & Answer only. If you want learn more about Python. Then you can visit below links to get more depth on this subject.




Join Our telegram group to ask Questions

Click below button to join our groups.