Hi, in this article let's learn how to find and count the number of local variables present in the function using python. Given a Python function name the sample so you have to count the number of local variables and printed in the main program so let's try to solve this.
Write a Python Program to Detect The Number of Local Variables Declared in a Function
Create sample function two local variables a and b and also return 0. given the sample function so you have to count the number of local variables in the main function.
In the main function try to use magic Method are double_method named as code and take a variable co_nlocals. co_nlocals Is a variable that will give us the number of local variables present in the function
Magic Method __code__ (or) Its is also refereed as dunder method (double underscore method)
Code 1
=============================
def sample():
a = 2
b = 3
return 0
print("No of Local Variables are : ", sample.__code__.co_nlocals)
OUTPUT
=======================
No of Local Variables are : 2
Write a Python Program to Detect The Number of Local Variables Declared in a Function having input argument
Now create sample function with two input arguments and two local variables a and b and also return 0. given the sample function so you have to count the number of local variables in the main function.
Code 2
=============================
def sample(arg1, arg2):
a = 2
b = 3
return 0
print("No of Local Variables are : ", sample.__code__.co_nlocals)
OUTPUT
=======================
No of Local Variables are : 4
Conclusion : Try to execute this program by yourself and change the variable names and let me know if there are any queries or suggestions in the comment section.
0 Comments