In this post, we’ll learn what Python nonLocal variable is and how to properly define and use it in code.
We’ll be using a practical Python code example with step by step explanation to better understand how Python nonLocal variable works.
After reading this article, you’ll have a practical knowledge of how to use Python nonLocal variables.
So without wasting anymore time, let’s just dive right into its practical implementation.
What is Python NonLocal Variable?
As the name suggests, this variable is not local nor global. This variable can be used in nested functions whose local scope is not defined. This specifies that the variable will not be in the local nor in global scope.
Let’s now understand it practically with proper example but first, let’s understand its syntax.
Syntax of NonLocal Variable
nonlocal variableName
In order to make a variable nonLocal, just write this nonlocal keyword before it.
Implementing Python NonLocal Variable (Easy Example Code)
For that, we have to create a nested function. See below code:
def fun(): val='Local Variable' // local variable created def nestedFun(): // nested function nonlocal val // local variable set to non local val='Non local Variable' // modifying the value of local variable which is now nonLocal print(val) // Non local Variable nestedFun() // call the nested function print(val) // Non local Variable fun() // call the function
Explanation of Code
We have first created a function and inside it we’ve created a local variable.
Then we have used a nested function and have made this variable non local by using the nonlocal keyword before this variable. After that, we have assigned a new value to it.
Now in the parent function, we’ve first made a call to this nested function which will print the modified value. After that, we also have printed the value of local variable to see if its modified or not.
As you can see that both the values are modified which means the nonlocal keyword has done its job.
Click here if you want to learn Python local variables in detail.
So this is how you can easily use Python nonLocal variable in your own code as well.
Feel free to ask if you still have any questions regarding the implementation of Python nonLocal variables. I’ll be very happy to answer all.
Conclusion
To conclude, hope you now you’ve a detailed practical understanding of how to properly use Python nonLocal variables. I’d be happy to have your feedback on this post. Thank you for reading it.