Default and Optional Parameters
Overview
Sometimes a function doesn't need every argument every time. You'll practice setting default values for parameters to make functions more flexible and easier to use, reducing the amount of code needed when calling functions with common settings.
What You Will Learn in This Lesson
By the end of this lesson, you will know:
- Default parameter values: Learn how to set default values for function parameters.
- Optional parameters: Understand how to make some parameters optional.
- Calling with defaults: Learn how to call functions with or without optional arguments.
- Best practices: Discover when and how to use default parameters effectively.
Why This Matters
Default parameters make your functions more flexible and easier to use. Instead of requiring all arguments every time, you can provide sensible defaults for common cases. This reduces code repetition and makes your functions more user-friendly - callers can provide only the arguments they need, and the function will use defaults for the rest.
Step 1: What Are Default Parameters?
Default parameters allow you to specify a default value for a parameter. If the caller doesn't provide that argument, Python uses the default value. This makes parameters optional - you can include them or leave them out when calling the function.
def greet(name, greeting="Hello"):
print(greeting + ", " + name)
greet("Alice") # Uses default: "Hello"
greet("Bob", "Hi") # Uses provided: "Hi"
Set Default Value
In the function definition, assign a default value to a parameter using =. In the example, greeting="Hello" means that if no greeting is provided, Python will use "Hello" as the default.
Call Without Argument
When you call the function without providing that argument, Python uses the default value. greet("Alice") uses the default greeting "Hello", so it prints "Hello, Alice".
Call With Argument
When you do provide the argument, Python uses your provided value instead of the default. greet("Bob", "Hi") uses "Hi" instead of the default, so it prints "Hi, Bob".
Key Concept: Default parameters must come after parameters without defaults. Python reads arguments from left to right, so if you want some parameters to be optional, they must be at the end of the parameter list.
Mini Practice #1: Using Default Parameters
Try It YourselfTry calling the function with and without the optional parameter:
What happened? When you call calculate_total(100) without providing tax_rate, Python uses the default value of 0.08 (8%). So the total is 100 * 1.08 = 108. When you call calculate_total(100, 0.10) with a provided tax rate, Python uses your value of 0.10 (10%) instead, giving you 100 * 1.10 = 110. Default parameters let you provide a common value while still allowing flexibility!
Step 2: Multiple Default Parameters
You can have multiple parameters with default values. All parameters with defaults must come after parameters without defaults:
def create_profile(name, age=18, city="Unknown"):
print(f"{name} is {age} years old, from {city}")
create_profile("Alice") # Uses both defaults
create_profile("Bob", 25) # Uses city default
create_profile("Charlie", 30, "Paris") # Provides all
How It Works
When you call the function, Python fills in arguments from left to right. If you provide create_profile("Bob", 25), Python assigns "Bob" to name, 25 to age, and uses the default "Unknown" for city. You can provide arguments in order, and Python will use defaults for any you skip at the end.
Step 3: Order Matters
Parameters without defaults must come before parameters with defaults. This is a Python rule that prevents ambiguity:
# ✅ CORRECT: Required parameters first
def greet(name, greeting="Hello"):
print(greeting + ", " + name)
# ❌ ERROR: Default parameter before required
def greet(greeting="Hello", name): # This won't work!
print(greeting + ", " + name)
Remember: Required parameters (without defaults) must come first, then optional parameters (with defaults) come after. If you try to put a default parameter before a required one, Python will give you a syntax error because it wouldn't know which argument goes to which parameter.
Mini Practice #2: Multiple Defaults
Try It YourselfTry calling the function with different combinations of arguments:
What happened? The function has one required parameter (name) and two optional parameters (prefix and suffix). When you call format_message("Alice"), Python uses the defaults for both prefix and suffix. When you call format_message("Bob", "Note"), Python uses "Note" for prefix and the default "!" for suffix. When you provide all three arguments, Python uses all your provided values. You can provide arguments in order, skipping any defaults you want to use!
Step 4: When to Use Default Parameters
Default parameters are useful when:
Common Values
When most calls use the same value, make it the default.
def calculate_area(width, length=1):
return width * length
# Most rectangles are squares
Optional Features
When some features are optional or rarely used.
def print_info(name, verbose=False):
# verbose is usually False
return name
Best Practices
Use default parameters for values that are commonly the same across most function calls. This makes your functions easier to use - callers don't have to repeat the same values over and over. However, don't use defaults for values that change frequently or are critical to the function's behavior.
End-of-Lesson Exercises
Exercise 1: Create a Function with Default Parameter
Create a function named greet that takes two parameters: name (required) and greeting (default value "Hello"). The function should print the greeting and name. Call it once with just the name, and once with both parameters.
Use a default value for the greeting parameter.
Exercise 2: Function with Multiple Default Parameters
Create a function named create_message that takes three parameters: name (required), prefix (default "Hi"), and suffix (default "!"). It should return a string formatted as "{prefix}, {name}{suffix}". Call it with different combinations of arguments.
Set default values for prefix and suffix, and make sure required parameters come first.