Function Arguments
Python lets you pass arguments in several flexible ways.
Positional & Keyword Arguments
Positional args are matched by order; keyword args are matched by name.
def describe_pet(animal, name):
print(f"I have a {animal} named {name}.")
describe_pet("dog", "Rex")
describe_pet(name="Whiskers", animal="cat")
Try it Yourself โ
Default Arguments
Assign a default value so the argument becomes optional.
def greet(name, greeting="Hello"):
print(f"{greeting}, {name}!")
greet("Alice")
greet("Bob", "Hi")
Try it Yourself โ
*args and **kwargs
*args captures extra positional args as a tuple. **kwargs captures extra keyword args as a dict.
def print_args(*args, **kwargs):
print("Positional:", args)
print("Keyword:", kwargs)
print_args(1, 2, 3, name="Alice", age=30)
Try it Yourself โ