In the previous tutorial, we explored the basics of defining and using functions in Python. Functions are essential building blocks for writing modular and reusable code. However, sometimes you need to write functions that can accept a varying number of arguments. This is where *args and **kwargs come into play.
*args and **kwargs allow functions to handle a variable number of positional and keyword arguments respectively. Understanding how to use these features will make your functions more flexible and adaptable to different scenarios.
In this tutorial, we'll cover:
Positional arguments are the most common type of function arguments. They are passed to functions in the order they are defined.
1def greet(name, age):2print(f"Hello {name}, you are {age} years old.")34greet("Alice", 30)
Hello Alice, you are 30 years old.
Keyword arguments allow you to specify the name of the parameter when passing an argument to a function. This makes the code more readable and flexible.
1def greet(name, age):2print(f"Hello {name}, you are {age} years old.")34greet(age=30, name="Alice")
Hello Alice, you are 30 years old.
Default parameter values allow a function to be called with fewer arguments than it is defined to accept. If an argument is not provided when the function is called, the default value is used.
1def greet(name, age=25):2print(f"Hello {name}, you are {age} years old.")34greet("Alice")5greet("Bob", 30)
Hello Alice, you are 25 years old. Hello Bob, you are 30 years old.
*args allows a function to accept any number of positional arguments as a tuple.
1def add(*args):2return sum(args)34result = add(1, 2, 3, 4)5print(result)
10
**kwargs allows a function to accept any number of keyword arguments as a dictionary.
1def display_info(**kwargs):2for key, value in kwargs.items():3print(f"{key}: {value}")45display_info(name="Alice", age=30, city="New York")
name: Alice age: 30 city: New York
Let's create a practical example that combines the use of positional arguments, default values, *args, and **kwargs.
1def report(name, age=25, *hobbies, **details):2print(f"Name: {name}")3print(f"Age: {age}")4if hobbies:5print("Hobbies:", ", ".join(hobbies))6for key, value in details.items():7print(f"{key}: {value}")89report("Alice", 30, "reading", "hiking", country="USA", occupation="Engineer")
Name: Alice Age: 30 Hobbies: reading, hiking country: USA occupation: Engineer
In the next tutorial, we'll explore Python Lambda Functions. These are small anonymous functions defined with the lambda keyword. They are useful for short, throwaway functions and can be used wherever function objects are required.
Stay tuned!