Course Content
Python Indentation, Comments and Variables
0/2
Object Oriented Programming in Python
0/1
Exception Handling in Python
0/1
Sending emails with Python
0/1
Unit test in python programming
0/1
Python programming (zero to advance!!!)
About Lesson

Counting parameters

Define a function param_count that takes a variable number of parameters. The function should return the number of arguments it was called with.

For example, param_count() should return 0, while param_count(2, 3, 4) should return 3.

 

==== SOLUTION ====

You can achieve this by using the special variable `*args`, which collects all positional arguments into a tuple within the function. Then, you can return the length of this tuple. Here’s how you can do it:

“`python
def param_count(*args):
       return len(args)

# Test cases
print(param_count()) # Output: 0
print(param_count(2, 3, 4)) # Output: 3
“`

Explanation:

1. `def param_count(*args):`: This line defines a function named `param_count` that accepts a variable number of positional arguments using `*args`.

2. `return len(args)`: This line returns the length of the `args` tuple, which represents the number of arguments passed to the function.

This implementation correctly counts the number of parameters passed to the function, regardless of how many there are.

 

Join the conversation