Python Tutorial

Python Variable

Python Operators

Python Sequence

Python String

Python Flow Control

Python Functions

Python Class and Object

Python Class Members (properties and methods)

Python Exception Handling

Python Modules

Python File Operations (I/O)

Python default arguments

In Python, you can define functions with default argument values. These default values are used when a value for a specific argument is not provided by the caller. Default arguments can make your functions more flexible and easier to use.

Here's a tutorial on default arguments in Python:

  • Basic Syntax

To set a default value for a function argument, use the assignment operator = in the function definition:

def function_name(arg1=default_value1, arg2=default_value2):
    # function body
  • Using default arguments

Here's an example of using default arguments in a function:

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

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

In this example, the greet function has two arguments: name and greeting. The greeting argument has a default value of "Hello". When the function is called without providing a value for greeting, the default value is used.

  • Positional and keyword arguments with default values

You can mix positional and keyword arguments in a function call, and they will be matched in the correct order. However, once you use a keyword argument, all subsequent arguments must also be keyword arguments:

def display_info(name, age, country="Unknown"):
    print(f"Name: {name}, Age: {age}, Country: {country}")

display_info("Alice", 30)  # Output: Name: Alice, Age: 30, Country: Unknown
display_info("Bob", 25, "USA")  # Output: Name: Bob, Age: 25, Country: USA
display_info("Charlie", 35, country="UK")  # Output: Name: Charlie, Age: 35, Country: UK
  • Default argument pitfalls

When using mutable objects, like lists or dictionaries, as default argument values, you may encounter unexpected behavior. The default argument is evaluated only once when the function is defined, so the same object will be used for all function calls that don't provide a value for the argument:

def add_item(item, items=[]):
    items.append(item)
    return items

print(add_item(1))  # Output: [1]
print(add_item(2))  # Output: [1, 2], not [2] as expected

To avoid this pitfall, use None as the default value and create a new object inside the function if no value is provided:

def add_item(item, items=None):
    if items is None:
        items = []
    items.append(item)
    return items

print(add_item(1))  # Output: [1]
print(add_item(2))  # Output: [2]

In summary, default arguments in Python allow you to define functions with default values for specific arguments, making your functions more flexible and easier to use. Be aware of the pitfalls when using mutable objects as default argument values, and use None as a sentinel value to avoid unexpected behavior.

  1. How to use default arguments in Python functions:

    • Description: Assign default values to parameters in a function, allowing the function to be called without providing values for those parameters.
    • Code:
      def greet(name, greeting="Hello"):
          print(f"{greeting}, {name}!")
      
      greet("Alice")  # Uses default greeting
      greet("Bob", greeting="Hi")  # Overrides default greeting
      
  2. Default parameter values in Python functions:

    • Description: Specify default values directly in the function definition for parameters.
    • Code:
      def power(base, exponent=2):
          return base ** exponent
      
      result = power(3)  # Uses default exponent value of 2
      
  3. Overriding default arguments in Python:

    • Description: Provide explicit values for parameters, overriding their default values.
    • Code:
      def multiply(a, b=2):
          return a * b
      
      result = multiply(5, 3)  # Overrides default value of b
      
  4. Mutable default arguments and potential issues:

    • Description: Be cautious when using mutable objects (e.g., lists or dictionaries) as default values to avoid unexpected behavior.
    • Code:
      def add_item(item, my_list=[]):
          my_list.append(item)
          return my_list
      
      result1 = add_item("apple")
      result2 = add_item("banana")  # Unexpected behavior due to mutable default argument
      
  5. Named default arguments in Python functions:

    • Description: Specify values for parameters by name, allowing flexibility in argument order.
    • Code:
      def create_person(name, age=30, city="New York"):
          print(f"Name: {name}, Age: {age}, City: {city}")
      
      create_person("Alice")
      create_person("Bob", city="San Francisco")
      
  6. Handling variable-length argument lists with default arguments:

    • Description: Use default values to handle variable-length argument lists, providing flexibility in function calls.
    • Code:
      def print_items(*args, separator=", "):
          items_str = separator.join(map(str, args))
          print(items_str)
      
      print_items("apple", "orange", "banana")  # Uses default separator
      print_items("apple", "orange", "banana", separator="-")  # Overrides separator
      
  7. Type hints and default arguments in Python:

    • Description: Combine type hints with default arguments to provide additional information about expected parameter types.
    • Code:
      def repeat_string(s: str, times: int = 2) -> str:
          return s * times
      
  8. Using default arguments with lambda functions in Python:

    • Description: Create lambda functions with default arguments for concise, inline functionality.
    • Code:
      power = lambda base, exponent=2: base ** exponent
      result = power(3)  # Uses default exponent value of 2
      
  9. Avoiding mutable default arguments in Python:

    • Description: Use immutable default values or None along with a check inside the function to avoid mutable default argument issues.
    • Code:
      def add_item(item, my_list=None):
          if my_list is None:
              my_list = []
          my_list.append(item)
          return my_list
      
  10. Default arguments vs. keyword arguments in Python:

    • Description: Understand the difference between default arguments and explicitly passing values using keyword arguments.
    • Code:
      def greet(name, greeting="Hello"):
          print(f"{greeting}, {name}!")
      
      greet("Alice")  # Uses default greeting
      greet("Bob", greeting="Hi")  # Overrides using keyword argument