Python - Default Arguments

Hello there, aspiring Python programmers! Today, we're going to dive into the wonderful world of default arguments in Python. As your friendly neighborhood computer science teacher, I'm excited to guide you through this journey. So, grab your favorite beverage, get comfortable, and let's embark on this Python adventure together!

Python - Default Arguments

What Are Default Arguments?

Before we jump into the nitty-gritty, let's start with the basics. Default arguments are a nifty feature in Python that allows you to define function parameters with pre-set values. These values will be used if you don't provide a specific value when calling the function.

Think of default arguments as a safety net. They're there to catch you if you forget to specify a value, ensuring your function can still run smoothly. It's like having a friend who always brings extra snacks to a picnic – you might not always need them, but it's great to have them just in case!

Why Use Default Arguments?

  1. They make your code more flexible.
  2. They reduce the number of arguments you need to provide.
  3. They help maintain backward compatibility when adding new parameters to functions.

Now, let's see how this works in practice!

Example of Default Arguments

Let's start with a simple example. Imagine we're creating a function to greet people:

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

# Using the function
print(greet("Alice"))
print(greet("Bob", "Hi"))

Output:

Hello, Alice!
Hi, Bob!

In this example, greeting is our default argument. If we don't specify a greeting, the function will use "Hello" by default. Let's break it down:

  1. We defined the greet function with two parameters: name and greeting.
  2. greeting has a default value of "Hello".
  3. When we call greet("Alice"), we only provide the name. The function uses the default "Hello" for the greeting.
  4. When we call greet("Bob", "Hi"), we provide both name and greeting, so the function uses "Hi" instead of the default.

Example: Calling Function Without Keyword Arguments

Now, let's look at a slightly more complex example. We'll create a function to calculate the total cost of items in a shopping cart:

def calculate_total(items, tax_rate=0.08, discount=0):
    subtotal = sum(items)
    total = subtotal * (1 + tax_rate) - discount
    return round(total, 2)

# Using the function
cart1 = [10, 20, 30]
print(calculate_total(cart1))
print(calculate_total(cart1, 0.10))
print(calculate_total(cart1, 0.10, 5))

Output:

64.80
66.00
61.00

Let's break this down:

  1. Our calculate_total function has three parameters: items (required), tax_rate (default 0.08), and discount (default 0).
  2. In the first call, we only provide items. The function uses the default tax rate and no discount.
  3. In the second call, we provide items and a custom tax rate of 0.10. The discount remains 0.
  4. In the third call, we provide all three arguments: items, tax rate, and a discount of 5.

Remember, when calling a function without keyword arguments, the order matters! Python assigns values to parameters in the order they're provided.

Mutable Objects as Default Arguments

Now, here's where things get a bit tricky. Using mutable objects (like lists or dictionaries) as default arguments can lead to unexpected behavior. Let me show you what I mean:

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

print(add_item("apple"))
print(add_item("banana"))
print(add_item("cherry"))

Output:

['apple']
['apple', 'banana']
['apple', 'banana', 'cherry']

Surprise! The list keeps growing with each call. This happens because the default list is created only once when the function is defined, not each time the function is called.

To avoid this, we can use None as the default and create a new list inside the function:

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

print(add_item("apple"))
print(add_item("banana"))
print(add_item("cherry"))

Output:

['apple']
['banana']
['cherry']

Much better! Now each call creates a new list as expected.

Summary of Python Default Arguments

Let's summarize what we've learned in a handy table:

Concept Description Example
Basic Default Argument Provides a default value for a parameter def greet(name, greeting="Hello"):
Multiple Default Arguments A function can have multiple default arguments def calculate_total(items, tax_rate=0.08, discount=0):
Order of Arguments Non-default arguments must come before default arguments in the function definition def func(required, optional=default):
Mutable Default Arguments Avoid using mutable objects as default arguments Use None as default and create the object inside the function
Keyword Arguments Allow calling functions with named arguments in any order calculate_total(items=[10, 20], discount=5)

And there you have it, folks! You've just leveled up your Python skills with default arguments. Remember, like any powerful tool, use them wisely. They can make your code more flexible and easier to use, but be careful with those mutable defaults!

Keep practicing, stay curious, and happy coding! Before you know it, you'll be writing Python like a pro. Until next time, this is your friendly neighborhood CS teacher, signing off!

Credits: Image by storyset