In Python, a function is a group of related statements that performs a specific task. Functions help break our program into smaller and modular chunks to prevent code redundancy.
You might encounter scenarios that require you to send more than one argument to a function. This tutorial will guide you on how to pass multiple arguments in Python.
1. Using Default Arguments
Python allows us to provide default values to our function parameters. The arguments can then be called by the function despite the number of parameters provided. If we don’t provide any value to a default argument while calling the function, it carries its default value.
1 2 3 4 5 |
def introduce(name, greeting='Hello'): print(greeting, name) introduce('John') introduce('John', 'Welcome') |
The output would be:
Hello John Welcome John
2. Using Arbitrary Arguments
Sometimes, we don’t know in advance the number of arguments that will be passed into a function. Python allows us to handle this kind of situation through function calls with an arbitrary number of arguments.
1 2 3 4 5 |
def introduce(*names): for name in names: print('Hello', name) introduce('John', 'Mike', 'Emma') |
The output would be:
Hello John Hello Mike Hello Emma
3. Using Keyword Arguments
When we call functions in this manner, the order (position) of the arguments can be changed. This process is referred to as Keyword Arguments. We use the name (keyword) instead of the position to specify the arguments to the function.
1 2 3 4 |
def describe_pet(animal, petname): print("\nI have a " + animal + " and its name is " + petname) describe_pet(petname="Tommy", animal="dog") |
The output would be:
I have a dog and its name is Tommy
Complete Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
def introduce(name, greeting='Hello'): print(greeting, name) introduce('John') introduce('John', 'Welcome') def introduce(*names): for name in names: print('Hello', name) introduce('John', 'Mike', 'Emma') def describe_pet(animal, petname): print("\nI have a " + animal + " and its name is " + petname) describe_pet(petname="Tommy", animal="dog") |
Conclusion
In Python, passing multiple arguments to a function is simple and provides great flexibility in your code. Python provides various forms of functions that allow for flexibility in handling both the number of arguments and the holding of positional arguments. Always refer to the Python documentation for more detailed information.