The Wayback Machine - https://web.archive.org/web/20230512160711/https://www.geeksforgeeks.org/python-program-to-find-number-of-local-variables-in-a-function/
Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Python program to find number of local variables in a function

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

Given a Python program, task is to find the number of local variables present in a function.

Examples:

Input : a = 1
        b = 2.1
        str = 'GeeksForGeeks'
    
Output : 3

We can use the co_nlocals() function which returns the number of local variables used by the function to get the desired result.

Code #1:




# Implementation of above approach
  
# A function containing 3 variables 
def fun():
    a = 1
    str = 'GeeksForGeeks'
  
  
# Driver program
print(fun.__code__.co_nlocals)

Output:

2

 
Code #2:




# Python program to find number of
# local variables in a function
  
# A function containing no variables 
def geek():
    pass
  
# A function containing 3 variables 
def fun():
    a, b, c = 1, 2.25, 333
    str = 'GeeksForGeeks'
  
# Driver program
print(geek.__code__.co_nlocals)
print(fun.__code__.co_nlocals)

Output:

0
4
My Personal Notes arrow_drop_up
Last Updated : 10 Jan, 2019
Like Article
Save Article
Similar Reads
Related Tutorials