Passing Arguments to Functions
Positional Arguments
The most common way to pass arguments to a function is by using positional arguments. The arguments are passed in the same order as they are defined in the function definition.
def greet(name, message):
print(f"{message}, {name}!")
greet("Alice", "Hello") ## Output: Hello, Alice!
greet("Bob", "Good morning") ## Output: Good morning, Bob!
Keyword Arguments
You can also pass arguments using keyword arguments, where you specify the parameter name and its corresponding value.
def greet(name, message):
print(f"{message}, {name}!")
greet(name="Alice", message="Hello") ## Output: Hello, Alice!
greet(message="Good morning", name="Bob") ## Output: Good morning, Bob!
Default Arguments
Functions can have default values for their parameters, which are used if no argument is provided during the function call.
def greet(name, message="Hello"):
print(f"{message}, {name}!")
greet("Alice") ## Output: Hello, Alice!
greet("Bob", "Good morning") ## Output: Good morning, Bob!
Arbitrary Arguments (*args)
If you don't know in advance how many arguments a function will receive, you can use the *args
syntax to accept an arbitrary number of positional arguments.
def sum_numbers(*args):
total = 0
for num in args:
total += num
return total
print(sum_numbers(1, 2, 3)) ## Output: 6
print(sum_numbers(4, 5, 6, 7, 8)) ## Output: 30
Keyword Arguments (**kwargs)
Similar to *args
, you can use **kwargs
to accept an arbitrary number of keyword arguments.
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_info(name="Alice", age=25, city="New York")
## Output:
## name: Alice
## age: 25
## city: New York
Understanding these argument-passing techniques will help you write more flexible and powerful functions in Python.