Python Function: Calling functions with flexible arguments
Python ellipsis (...) Data Type: Exercise-2 with Solution
Write a Python function that takes a function as an argument and calls it with any number of arguments.
Sample Solution:
Code:
def call_function(func, *args, **kwargs):
"""
Calls the given function with any number of positional and keyword arguments.
Args:
func (function): The function to call.
*args: Any positional arguments to pass to the function.
**kwargs: Any keyword arguments to pass to the function.
Returns:
The result of calling the function.
"""
return func(*args, **kwargs)
# Example usage:
def add(x, y):
return x + y
result = call_function(add, 10, 22)
print(result) # Output: 8
def message(name, text="Good Evening"):
return f"{name}, {text}!"
result = call_function(message, "Erich", text = ...)
print(result)
Output:
32 Erich, Ellipsis!
In the exercise above, the "call_function()" function takes a 'func' argument, which is the function to call, and uses *args and **kwargs to accept any number of positional and keyword arguments. It then calls 'func' with these arguments and returns the result. As a result, you can call different functions with different numbers of arguments by using the same "call_function ()".
In this code, the ellipsis (...) is used as a placeholder for unspecified arguments in the function calls 'add' and 'message'. It indicates that there can be additional positional or keyword arguments.
Flowchart:

Previous: Python Function: Printing arguments with *args.
Next: Python Function: Slicing the third dimension of a multidimensional array.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
Python: Tips of the Day
Summing a sequence of numbers (calculating the sum of zero to ten with skips):
>>> l = range(0,10,2) >>> sum(l) 20
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook