4 2 Function Arguments Explained
Key Concepts
Function arguments in Python allow you to pass data into a function. The key concepts include:
- Positional Arguments
- Keyword Arguments
- Default Arguments
- Variable-Length Arguments (*args and **kwargs)
1. Positional Arguments
Positional arguments are the most common type of arguments. They are passed to a function in the order they are defined.
Example:
def greet(name, age): print(f"Hello, {name}! You are {age} years old.") greet("Alice", 25)
In this example, "Alice" is passed as the first argument (name) and 25 as the second argument (age).
2. Keyword Arguments
Keyword arguments allow you to pass arguments to a function by specifying the parameter name. This makes the function call more readable and allows you to pass arguments in any order.
Example:
def greet(name, age): print(f"Hello, {name}! You are {age} years old.") greet(age=25, name="Alice")
Here, the arguments are passed using their parameter names, so the order does not matter.
3. Default Arguments
Default arguments allow you to specify a default value for a parameter. If the argument is not provided when the function is called, the default value is used.
Example:
def greet(name, age=18): print(f"Hello, {name}! You are {age} years old.") greet("Alice") greet("Bob", 30)
In this example, if the age is not provided, it defaults to 18.
4. Variable-Length Arguments (*args and **kwargs)
Variable-length arguments allow a function to accept an arbitrary number of arguments. *args is used for non-keyworded variable-length arguments, and **kwargs is used for keyworded variable-length arguments.
Example with *args:
def add(*args): return sum(args) print(add(1, 2, 3)) # Output: 6 print(add(1, 2, 3, 4, 5)) # Output: 15
Example with **kwargs:
def display_info(**kwargs): for key, value in kwargs.items(): print(f"{key}: {value}") display_info(name="Alice", age=25, city="New York")
In these examples, *args allows the function to accept any number of positional arguments, and **kwargs allows it to accept any number of keyword arguments.
Putting It All Together
By understanding and using positional, keyword, default, and variable-length arguments, you can create more flexible and powerful functions in Python. These techniques allow you to handle various scenarios and make your code more readable and maintainable.
Example:
def greet(name, age=18, *args, **kwargs): print(f"Hello, {name}! You are {age} years old.") if args: print("Additional information:", args) if kwargs: print("Extra details:") for key, value in kwargs.items(): print(f"{key}: {value}") greet("Alice", 25, "Loves Python", hobby="Coding", city="New York")