Find Number of Variables in a Python Program Using a Function

Here’s the high-quality tutorial; it’s clear,beginner-friendly, and demonstrates how to find the number of variables in a Python program using a function.

How to Find the Number of Variables in a Python Program Using a Function

When working on larger Python projects, it’s often useful to analyze your code– for example, to count how many variables you have declared. In this tutorial, you’ll learn how to find the number of variables in a Python program using a custom function.

This can be especially helpful for:

  • Beginners who want to understand variable usage.
  • Static code analysis.
  • Debugging or refactoring large codebases.

What Are Variables in Python?

Variables in Python are simply names that refer to values stored in memory. For example:

x = 10
name = "Python"

Here, and name are variables.

Goal of This Tutorial

We will write a Python function that counts how many user-defined variables exist in a program. This includes variables defined in:

  • Global scope
  • Local function scope

We’ll ignore built-in or system variables.

Example Code-Count variables using globals() and locals()

Let’s break it down into a working example.

Step 1:Define Some Variables

a = 5
b = "hello"
c = [1, 2, 3]

Step 2: Create a Function to Count Variables

def count_variables():
    global_vars = globals()
    user_defined = [var for var in global_vars if not var.startswith("__") and not callable(global_vars[var])] 
    return len(user_defined)

Step 3: Run the Function

print("Number of variables:", count_variables())

Output:

Number of variables: 3

Full Working Example

a = 5
b = 'hello'
c = [1, 2, 3]
def count_variables():
    global_vars = globals()
    user_defined = [var for var in global_vars if not var.startswith("__") and not callable(global_vars[var])]
    return len(user_defined)
print("Number of variables:", count_variables())

Explanation

1. globals() returns a dictionary of all global names(including functions, classes, etc.).

2. We use list comprehension to filter out: 

  •  Built-in variables(which usually start and end with double underscores like  __name__).
  • Functions and callable (to count only real variables).

3. The length of this filtered list is the number of user-defined variables.

Note for Local Scope

If you want to count local variables inside a function, use locals() instead:

def sample():
    x = 10
    y = 20
    local_vars = locals()
    print("Local variables:", len(local_vars))
sample()

Bonus: Combine Global and Local Variable Count

a = 1
b = 2
def demo():
    x = 10
    y = 20
    global_vars = [var for var in globals() if not var.startswith("__") and not callable(globals()[var])]
    local_vars = locals()
    print("Total variables:", len(global_vars) + len(local_vars))

demo()

Conclusion

With this simple trick using globals() and locals(), you can easily count the number of variables in your Python program. It’s a great way to start exploring static code analysis or improve code readability.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top