Accept a variable number of arguments with args #
In some cases, we may not know in advance how many arguments will be passed to a function. Python allows us to accept an unlimited number of arguments by creating a function and specifying a variable with an asterisk symbol *, such as:
def say_hello(*args):
for name in args:
print(f"Hello {name}")
say_hello("Jacob", "Jordan", "Andrew")
Output:
Hello Jacob
Hello Jordan
Hello Andrew
When the function is called, all arguments are turned into a tuple that is assigned to the args variable, which we can loop through. If we define additional variables, the values specified in the function call will be assigned to those variables, and any remaining values will be collected into a tuple. For example:
def say_hello(first_person, *args):
print(f"The first person on the list is {first_person}")
for name in args:
print(f"Hello {name}")
say_hello("Jacob", "Jordan", "Andrew")
Output:
The first person on the list is Jacob
Hello Jordan
Hello Andrew
Exercise #
Create a function named accept_all that accepts any number of positional arguments.
Tests #
- Create a function named
accept_all - Function
accept_allshould accept any number of positional arguments
Getting Started with Python
Data Types
Python Functions
Statements in Python
Basic Debugging in Python
Basic Algorithm
Object-Oriented Programming
Error Handling
Intermediate Algorithm
Python Modules