Explanatory Question
What is Local Variables in Python?
Read the answer carefully and go through the related questions on the right side to improve your understanding of this topic.
A variable declared inside the function's body or in the local scope is known as a local variable.
def foo():
y = "local"
foo()
print(y)
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.
Normally, we declare a variable inside the function to create a local variable.
def foo():
y = "local"
print(y)
foo()
local
First read the answer fully, then try to explain it in your own words. After that, open a few related questions and compare the concepts. This method helps you remember the topic for a longer time and improves exam preparation.