Using Default Arguments

Python does not support traditional function overloading as seen in other languages like C++ or Java. Instead, it allows similar behavior using default arguments and variable-length arguments.

Key Concepts

  1. Default Arguments: Specify default values for parameters in a function definition.
  2. Variable-Length Arguments: Use *args and **kwargs to accept arbitrary numbers of positional and keyword arguments.

Using Default Arguments

Default arguments allow you to define functions that can be called with different numbers of arguments.

Example

def greet(name, message="Hello"):
    print(f"{message}, {name}!")

greet("Alice")          # Output: Hello, Alice!
greet("Bob", "Welcome") # Output: Welcome, Bob!

Explanation

  • Default Value: message has a default value of "Hello".
  • Flexibility: You can call greet with just the name or both name and message.

Using Variable-Length Arguments

Variable-length arguments enable functions to handle more flexible input.

Example

def add_numbers(*args):
    return sum(args)

print(add_numbers(1, 2, 3))       # Output: 6
print(add_numbers(10, 20, 30, 40)) # Output: 100

Explanation

  • *args: Collects all positional arguments into a tuple.
  • Sum Calculation: Uses sum() to add all numbers.

Combining Default and Variable-Length Arguments

You can combine default and variable-length arguments for greater flexibility.

Example

def display_info(name, age=30, *hobbies):
    print(f"Name: {name}, Age: {age}")
    if hobbies:
        print("Hobbies:", ", ".join(hobbies))

display_info("Alice", 25, "Reading", "Cycling")
# Output: Name: Alice, Age: 25
#         Hobbies: Reading, Cycling

display_info("Bob")
# Output: Name: Bob, Age: 30

Explanation

  • Default Argument (age): Has a default value of 30.
  • *hobbies: Accepts any number of additional arguments, which are treated as hobbies.

Keyword Arguments with **kwargs

Using **kwargs, you can accept any number of keyword arguments.

Example

def print_details(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

print_details(name="Alice", age=25, city="New York")
# Output: name: Alice
#         age: 25
#         city: New York

Explanation

  • **kwargs: Collects keyword arguments into a dictionary.
  • Flexibility: Allows passing any number of named arguments.