Function Arguments
Python Function Arguments
In Python, function arguments are the values that you pass to a function when calling it. Functions can have different types of arguments, including:
1. Positional Arguments:
def add(x, y):
return x + y
result = add(3, 4)
2. Keyword Arguments:
def greet(name, greeting="Hello"):
print(f"{greeting}, {name}!")
greet("Alice", greeting="Hi")
3. Default Values:
def power(base, exponent=2):
return base ** exponent
result = power(3) # Uses default exponent (2)
4. Arbitrary Number of Positional Arguments (\*args):
def print_arguments(*args):
for arg in args:
print(arg)
print_arguments(1, "hello", [3, 4])
5. Arbitrary Number of Keyword Arguments (\*\*kwargs):
def print_kwargs(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_kwargs(name="Alice", age=30, city="Wonderland")
6. Mixing Positional, Default, and Arbitrary Arguments:
def complex_function(x, y=10, *args, **kwargs):
# Code using x, y, args, and kwargs
pass
You can mix different types of arguments in a function definition. Positional arguments, default arguments, *args
for variable positional arguments, and **kwargs
for variable keyword arguments can all be used together.
Argument Order:
When defining a function, the order of the arguments generally follows this pattern:
- Positional arguments
- Default arguments
*args
(variable positional arguments)**kwargs
(variable keyword arguments)
When calling a function, you typically provide values in the same order: positional arguments first, followed by keyword arguments.
# Function definition
def example_function(arg1, arg2, default_arg=3, *args, **kwargs):
# Function body
# Function call
example_function(1, 2, default_arg=4, 5, 6, key1='value1', key2='value2')
Understanding how to use and combine these different types of function arguments allows you to create flexible and versatile functions in Python.