Default arguments allow you to assign default values to function parameters.
A function can include multiple parameters with default values.
In a function definition, non-default parameters must come before default parameters to avoid syntax errors.
In Python, default
Default arguments are specified directly in the function definition using the following syntax:
param_name = default_value
Here's how it works:
Below is a function that performs basic arithmetic operations on two numbers.
def calculate(x, y, action="add"):if action == "add":return x + yelif action == "subtract":return x - yelse:print("Invalid action")# Using the default actionresult = calculate(5, 3)print("Result with default argument: ", result)difference = calculate(5, 3, "subtract")print("Result without default argument: ", difference)
The default operation/action is addition, but we can specify subtraction or other actions by providing the action
argument.
Default arguments can make our code more flexible and user-friendly by providing sensible defaults while allowing customization when necessary. They also help us avoid errors and make our code more readable by providing sensible defaults.
We should know a few essential points before we look at more examples of using default arguments in functions.
We can have various parameters with default values. Here's an example:
def introduce_animal(name, type_of_animal="dog", age=1, color="brown"):print("The zoo has a", color, type_of_animal, "named", name, "who is ", age, " year(s) old.")# Using default values for type_of_animal, age, and colorintroduce_animal("Maxi")# Overriding the default value for type_of_animalintroduce_animal("Tiffy", "elephant")# Overriding the default values for type_of_animal, age, and colorintroduce_animal("Bella", "cat", 2, "white")# Overriding the default values for type_of_animal and ageintroduce_animal("Rocky", "giraffe", 3)
In this function, the type_of_animal
parameter has a default value of "dog"
, age
defaults to 1
, and color
defaults to "brown"
. If no specific values are provided when the function is called, these defaults are used automatically.
Having multiple parameters with default values—such as type_of_animal
, age
, and color
—makes it more convenient to call the function without specifying all the details each time.
When defining functions with default arguments, the order of parameters matters. Non-default parameters must come before default parameters. Here's an example of incorrect order:
def incorrect_order(type_of_animal="dog", name):print("I have a ", type_of_animal, " named ", name,".")
When running the code above, we get a syntax error. That's because we wrote the default parameter before the non-default parameter.
There are many scenarios where default arguments can help provide flexibility and convenience. Below are some examples:
One use case is sending emails to recipients with varying subjects and messages. Setting a default subject or message ensures that emails always include essential content, even if the sender forgets to provide it. This helps maintain a consistent and professional communication format.
def generate_email(to, subject = "No Subject", body="Please drop us a note if you have any other questions or concerns."):print("Sending email to ", to)print("Subject: ", subject)print("Body: ", body, "\n")generate_email("sarah@example.com") # Uses default subject and bodygenerate_email("dave@example.com", "Meeting Reminder") # Uses default bodygenerate_email("kate@example.com", "Invitation", "Join us for a party!") # No defaults used
to
: This parameter does not have a default value, so it is required when calling the function.
subject
: This parameter has a default value of "No Subject"
. If no value is passed for subject
, it uses this default value.
body
: This parameter has a default value of Please drop us a note if you have any other questions or concerns.
(it could also be left empty with an empty string ""
). If no value is passed for body
, it uses the default value.
Another use case is when creating user profiles. Setting default values for fields such as the profile picture and bio simplifies the registration process, allowing users to complete their profiles quickly without filling in every detail.
Users can customize their profiles later, but having default values ensures the initial profiles are functional and complete.
def create_profile(username, bio="No bio provided", profile_pic="default.jpg"):print("Username: ",username)print("Bio: ", bio)print("Profile Picture: ", profile_pic)create_profile("john_doe") # Uses default bio and profile picturecreate_profile("jane_doe", "Loves hiking") # Uses default profile picturecreate_profile("sam_smith", "Photographer", "sam.jpg") # No defaults used
username
: This parameter does not have a default value, so it is required when calling the function.
bio
: This parameter has a default value of "No bio provided"
. If no value is passed for bio
, it uses this default value.
profile_pic
: This parameter has a default value of "default.jpg"
. If no value is passed for profile_pic
, it uses this default value.
Consider a real-life scenario involving a shopping cart system. You may want to calculate the total price of items with an optional discount. By default, the discount value is set to zero, which means no discount is applied unless explicitly specified.
In this example, we've created a function calculate_total
that calculates the total price of items in a shopping cart. The function has a default argument for the discount percentage.
def calculate_total(prices, discount=0):# Calculate the sum of all pricestotal = sum(prices)# Apply the discountif discount > 0:total *= (1 - discount / 100)return total# Example usageitem_prices = [19.99, 24.99, 4.99, 2.99]# Calculate total with no discounttotal_price_no_discount = calculate_total(item_prices)print("Total price with no discount: $", total_price_no_discount) # Results: $52.96# Calculate total with a 10% discounttotal_price_with_discount = calculate_total(item_prices, discount=10)print("Total price with 10% discount: $", total_price_with_discount) # Results: $47.66
Similarly, in various applications, default settings and preferences can be used until the user customizes them to their liking. In recommendation systems, default recommendations can be provided based on general user preferences if the user hasn’t provided specific preferences yet.
In each scenario, default arguments help streamline the user experience by providing sensible defaults that can be easily overridden.
Now that you’ve learned about default arguments, try creating your function using them. In the widget below, write a function named describe_book
That takes three parameters: author
, title
, and genre
. Set default values for the author
and genre
parameters.
This allows you to call the function with just the title if needed, while still having meaningful defaults in place for the other values.
# Complete the function definition below.def describe_book():describe_book("Emma")describe_book("Jane Eyre", "Charlotte Bronte")describe_book("The Great Gatsby", "F. Scott Fitzgerald", "Classic")
Free Resources