In Python, functions can take various types of arguments. These include:
Positional Arguments
Keyword Arguments
Default Arguments
Variable-Length Arguments
Let's go through each type with examples:
Positional arguments are the most common type. The values are assigned to parameters in the order they are passed.
def greet(name, age):
print(f"Hello, my name is {name} and I am {age} years old.")
greet("Alice", 30) # Output: Hello, my name is Alice and I am 30 years old.
m 30 years old.
Keyword arguments are passed with the parameter names explicitly. This allows arguments to be passed in a different order.
def greet(name, age):
print(f"Hello, my name is {name} and I am {age} years old.")
greet(age=30, name="Alice") # Output: Hello, my name is Alice and I am 30 years old.
def greet(name, age):
print(f"Hello, my name is {name} and I am {age} years old.")
greet(age=30, name="Alice") # Output: Hello, my name is Alice and I am 30 years old.
d I am 30 years old.
Default arguments are used when you want a parameter to have a default value if no argument is provided.
def greet(name, age=25):
print(f"Hello, my name is {name} and I am {age} years old.")
greet("Alice") # Output: Hello, my name is Alice and I am 25 years old.
greet("Bob", 30) # Output: Hello, my name is Bob and I am 30 years old.
*args
*args allows a function to accept any number of positional arguments. These arguments are accessible as a tuple.
def greet(*names):
for name in names:
print(f"Hello, {name}!")
greet("Alice", "Bob", "Charlie")
# Output:
# Hello, Alice!
# Hello, Bob!
# Hello, Charlie!
Hello, Charlie!
**kwargs
**kwargs allows a function to accept any number of keyword arguments. These arguments are accessible as a dictionary.
def greet(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
greet(name="Alice", age=30, city="New York")
# Output:
# name: Alice
# age: 30
# city: New York
You can combine different types of arguments in a function. The order of parameters must be:
Positional arguments
*args
Keyword arguments
**kwargs
ars old. # Hello, Bob! You are 30 years old. # city: New York # hobby: reading
def greet(greeting, *names, age=30, **kwargs):
for name in names:
print(f"{greeting}, {name}! You are {age} years old.")
for key, value in kwargs.items():
print(f"{key}: {value}")
greet("Hello", "Alice", "Bob", city="New York", hobby="reading")
# Output:
# Hello, Alice! You are 30 years old.
# Hello, Bob! You are 30 years old.
# city: New York
# hobby: reading