Python Arguments
Functions in Python let you organize your code into reusable blocks. To make functions flexible and dynamic, you can pass arguments - pieces of data that the function uses when it runs.
This article covers the different ways to define and use function arguments in Python, with practical examples and clear explanations.
What Are Function Arguments?
Arguments are the values you provide to a function when calling it. These values are received by parameters defined in the function’s signature.
Example:
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
Output:
Hello, Alice!
name
is a parameter."Alice"
is an argument passed to the function.
Positional Arguments
These are the most common type of arguments. Their position in the function call matters.
def add(a, b):
print(a + b)
add(2, 3)
Output:
5
a
receives2
,b
receives3
.- The order must match the function definition.
Keyword Arguments
You can specify which parameter gets which value using the param=value
syntax. This makes the code clearer and allows you to change the order.
def describe_pet(animal, name):
print(f"{name} is a {animal}")
describe_pet(name="Buddy", animal="dog")
Output:
Buddy is a dog
- The function still works even if the arguments are passed in a different order.
Default Argument Values
You can assign default values to parameters. If no value is provided, the default is used.
def greet(name, greeting="Hello"):
print(f"{greeting}, {name}!")
greet("Alice")
greet("Bob", "Hi")
Output:
Hello, Alice!
Hi, Bob!
- If the second argument is not given, it defaults to
"Hello"
.
Variable-Length Arguments
Sometimes you don’t know how many arguments will be passed. Python supports this using:
*args (Non-keyword Variable Arguments)
Use *args
to pass a variable number of positional arguments.
def print_numbers(*args):
for num in args:
print(num)
print_numbers(1, 2, 3, 4)
Output:
1
2
3
4
args
is a tuple containing all the extra arguments.
**kwargs (Keyword Variable Arguments)
Use **kwargs
to pass a variable number of keyword arguments.
def print_user_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_user_info(name="Alice", age=30, country="France")
Output:
name: Alice
age: 30
country: France
kwargs
is a dictionary of key-value pairs.
Mixing Argument Types
You can mix different argument types, but the order matters:
- Positional arguments
- *args
- Keyword arguments
- **kwargs
def demo(a, b=2, *args, **kwargs):
print(f"a: {a}")
print(f"b: {b}")
print(f"args: {args}")
print(f"kwargs: {kwargs}")
demo(1, 3, 5, 6, x=10, y=20)
Output:
a: 1
b: 3
args: (5, 6)
kwargs: {'x': 10, 'y': 20}
Argument Unpacking
You can use *
and **
to unpack values into arguments.
def multiply(a, b):
print(a * b)
args = (3, 4)
multiply(*args) # same as multiply(3, 4)
Output:
12
def show_info(name, age):
print(f"{name} is {age} years old.")
kwargs = {"name": "Alice", "age": 30}
show_info(**kwargs)
Output:
Alice is 30 years old.
Summary
- Positional arguments: Order matters.
- Keyword arguments: Use names for clarity.
- Default values: Provide fallback values.
*args
and**kwargs
: Accept variable numbers of arguments.- Unpacking: Use
*
and**
to pass values from collections.
Understanding these argument types makes your functions more powerful and flexible. They're essential for writing clean, reusable Python code.
Continue Learning
Python Variables
Popular
### Understanding Variables and Literals in Python Variables and literals are the foundation of any
Personalized Recommendations
Log in to get more relevant recommendations based on your reading history.