Python Exercise: Detect the number of local variables declared in a function
Python Functions: Exercise - 20 with Solution
Write a Python program to detect the number of local variables declared in a function.
Sample Solution:
Python Code:
# Define a function named 'abc'
def abc():
# Define and assign values to local variables 'x', 'y', and 'str1' inside the function 'abc'
x = 1
y = 2
str1 = "w3resource"
# Print the string "Python Exercises"
print("Python Exercises")
# Access the number of local variables in the function 'abc' using the __code__.co_nlocals attribute
print(abc.__code__.co_nlocals)
Sample Output:
3
Explanation:
In the exercise above the code defines a function "abc()" that contains three local variables: 'x', 'y', and 'str1'. However, it only defines these variables and doesn't utilize them further. Then, it accesses the number of local variables defined in the "abc()" function using the abc.__code__.co_nlocals attribute and prints the result.
Flowchart:
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Python program to execute a string containing Python code.
Next: Write a Python program that invoke a given function after specific milliseconds.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://198.211.115.131/python-exercises/python-functions-exercise-20.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics