In this article, we’ll learn what Python local variable is and how to properly make use of it in Python code.
To better understand Python local variable, we’ll be using a practical Python code example with step by step explanation.
After reading this article, you’ll have a practical understanding of how to use local variables in Python.
So let’s just dive right into its practical implementation.
What is Python Local Variable?
It specifies a variable that is defined inside a function of Python or at some local scope. It can’t be accessed from outside of that function but can easily be accessed from inside of that specific function.
Let’s now properly understand how to define and use local variables in Python.
Implementing Python Local Variable (Easy Code Example)
Below section features the code example which will demonstrate how to make use of Python local variable.
Create and Fetch a Local Variable
def fun(): value='Local variable' // local variable is created print(value) // I will print the local variable fun() // call the function (fun()) print(value) // NameError: name 'value' is not defined
Local variable // fetching from inside of the same function NameError: name 'value' is not defined // fetching from outside of that function
In the above code, we have created a function and inside it, we’ve created our Python local variable. You can see that the value of local variable is fetched successfully from inside of that specific function. But when we tried to fetch it from outside that function then it gives a name error.
Reason is that creating a variable inside a function will make its scope local. It means that fetching this variable directly is possible only from the inside of that specific function. Fetching it from outside will give a name error.
So keep in mind that if you want to limit the scope or access of any variable to some specific function then create it inside that function.
Click here if you are interested in how to define and use Python global variable as well.
So this is how you can easily define and use Python local variable in your own code as well. Hope you like this post. Do implement it in your code and share your experience with us.
Feel free to ask if you have any questions regarding the implementation of Python local variable. I’ll be very happy to answer all your questions.
As a conclusion of this post, now you’ve a detailed practical understanding of how to use Python local variable. I’ll love to hear your thoughts on this post. Thank you for reading it.