In Python, arguments are the information or data we pass to functions so they can do something specific. Functions are like small programs inside your main program that solve one specific task.
Types of Arguments in Python
There are several types of arguments in Python:
- Positional Arguments
- Keyword Arguments
- Default Arguments
- Variable-Length Arguments (
*args
and**kwargs
)
Let’s explore each type with examples.
1. Positional Arguments
These are the most common type of arguments. The order in which you pass the arguments matters because Python assigns each value to the corresponding parameter in the function.
Example:
def greet(first_name, last_name):
print(f"Hello, {first_name} {last_name}!")
# Calling the function
greet("John", "Doe")
Output:
Hello, John Doe!
Here, "John"
is assigned to first_name
and "Doe"
to last_name
. If you switch their positions, the greeting will change.
Key Point:
- Order matters with positional arguments.
2. Keyword Arguments
With keyword arguments, you specify which value goes to which parameter by using the parameter’s name. This makes your function call more readable and eliminates the importance of the order.
Example:
def greet(first_name, last_name):
print(f"Hello, {first_name} {last_name}!")
# Calling the function with keyword arguments
greet(last_name="Doe", first_name="John")
Output:
Hello, John Doe!
Key Point:
- You can mix positional and keyword arguments, but keyword arguments must come after positional arguments.
3. Default Arguments
You can give a parameter a default value. If you don’t pass that argument, Python uses the default value.
Example:
def greet(first_name, last_name="Smith"):
print(f"Hello, {first_name} {last_name}!")
# Calling the function with one argument
greet("John") # Uses the default for last_name
# Calling the function with both arguments
greet("John", "Doe")
Output:
Hello, John Smith!
Hello, John Doe!
Key Point:
- Default arguments are great for optional parameters.
4. Variable-Length Arguments
Sometimes, you don’t know in advance how many arguments you’ll pass. Python lets you handle this with two special types of arguments:
*args
for a variable number of positional arguments**kwargs
for a variable number of keyword arguments
Example with *args
:
def sum_numbers(*numbers):
total = sum(numbers)
print(f"The sum is: {total}")
# Passing multiple arguments
sum_numbers(1, 2, 3, 4, 5)
Output:
The sum is: 15
Example with **kwargs
:
def show_user_details(**details):
for key, value in details.items():
print(f"{key}: {value}")
# Passing multiple keyword arguments
show_user_details(name="John", age=30, city="New York")
Output:
name: John
age: 30
city: New York
Key Points:
- Use
*args
when you need many positional arguments. - Use
**kwargs
when you need many keyword arguments.
Combining Different Types of Arguments
You can mix and match these argument types, but the order in the function definition should be:
- Positional arguments
- Default arguments
*args
**kwargs
Example:
def create_profile(name, age=25, *hobbies, **other_details):
print(f"Name: {name}")
print(f"Age: {age}")
print(f"Hobbies: {', '.join(hobbies)}")
for key, value in other_details.items():
print(f"{key}: {value}")
# Function call
create_profile(
"Alice",
30,
"reading", "traveling",
city="Paris", profession="Engineer"
)
Output:
Name: Alice
Age: 30
Hobbies: reading, traveling
city: Paris
profession: Engineer
Key Points:
- Always follow the proper order: positional -> default ->
*args
->**kwargs
. - Default arguments act as fallbacks.
*args
collects additional positional arguments into a tuple.**kwargs
collects additional keyword arguments into a dictionary.
Things to Watch Out For
- Misplacing Positional and Keyword Arguments
Positional arguments must come before keyword arguments when calling the function.# Incorrect greet(last_name="Doe", "John") # SyntaxError # Correct greet("John", last_name="Doe")
- Avoiding Ambiguity with Multiple Defaults
If both*args
and**kwargs
are used, they should follow the correct order, or Python will throw an error.
Practical Example: Calculator Function
Let’s build a calculator that can handle basic operations and takes arguments in multiple ways.
Code:
def calculator(a, b, operation="add", *args, **kwargs):
if operation == "add":
result = a + b
elif operation == "subtract":
result = a - b
elif operation == "multiply":
result = a * b
elif operation == "divide":
result = a / b
else:
result = None
print(f"Initial result: {result}")
if args:
print(f"Extra positional arguments: {args}")
if kwargs:
print(f"Additional settings: {kwargs}")
# Usage examples
calculator(10, 5, "multiply")
calculator(10, 5, "add", 2, 3, precision=2)
Output:
Initial result: 50
Initial result: 15
Extra positional arguments: (2, 3)
Additional settings: {'precision': 2}