w3resource

Python Exercise: Detect the number of local variables declared in a function


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:

Flowchart: Python exercises: Detect the number of local variables declared in a function.

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.



Follow us on Facebook and Twitter for latest update.