A Python optional argument is a type of argument with a default value. You can assign an optional argument using the assignment operator in a function definition or using the Python **kwargs statement.
There are two types of arguments a Python function can accept: positional and optional. Optional arguments are values that do not need to be specified for a function to be called.
In this guide, we talk about what optional arguments are and how they work.
We’ll walk you through an example of optional arguments so you can learn how to use them in your programs. We’ll also discuss how to use the **kwargs method to accept variable numbers of arguments.
What is a Python Argument?
An argument is a value that is accepted by a Python function. This value becomes its own Python variable that can be used within a function. Consider the following code:
def show_the_day(day): print("Hello there. Today is {}.".format(day)) show_the_day("Thursday")
In this code, “day” is an argument. Whatever value you specify in parentheses when you call the show_the_day function will become “day”. In this case, “Thursday” is “day”.
The number of values we specify in a function call must be equal to the number of arguments that a function accepts. This is unless we use optional arguments. In which case, we can specify fewer arguments than a function accepts because some arguments are optional.
Python Optional Arguments
A Python optional argument is an argument with a default value. You can specify a default value for an argument using the assignment operator. There is no need to specify a value for an optional argument when you call a function. This is because the default value will be used if one is not specified.
Arguments can have default values. This makes an argument optional. If an argument has a default value, then it will use that default value if no other value is specified.
Default arguments are assigned using the assignment operator:
def print_student(student, grade="Fifth"): print("{} is in {} grade.".format(student, grade))
This user-defined function accepts two arguments: student and grade. Grade is an optional function argument which means we do not need to specify a value for it when we call the print_student() function.
Optional Arguments Python Example
We’re going to write a program that counts how many of a particular coffee was sold at a coffee shop on a Thursday morning. To start, define a list of coffees that were sold that morning:
coffees_sold = ["Espresso", "Espresso", "Latte", "Cappuccino", "Mocha", "Espresso", "Latte"]
Next, write a function that counts how many of a particular coffee was sold:
def count_coffees(coffees, to_find="Espresso"): number_sold = coffees.count(to_find) print("{} {} coffees were sold.".format(number_sold, to_find))
This function accepts two arguments: coffees and to_find.
The first argument is the list of coffees. Our second argument is the name of the coffee whose total sales we want to calculate. The Python count() method counts how many instances of the coffee for which we are looking exists in the “coffees” list.
The second argument is optional. If we don’t specify a value for the “to_find” argument, that argument will become equal to “Espresso”. Next, let’s call the function:
count_coffees(coffees_sold, "Latte")
This function call will make the value of “to_find” equal to “Latte” in our code. Let’s run the program and see what happens:
2 Latte coffees were sold.
The code tells us that two lattes were sold. Now, call our function without a second value:
count_coffees(coffees_sold)
Our code returns:
3 Espresso coffees were sold.
We specified no value for “to_find” so, by default, its value became “Espresso”. We can see that if we specify no value for an argument, its default value is used. Otherwise, the value we specify is used for the argument.
Python Function Optional Arguments Error
Optional parameters must appear after required arguments when you define a function. Required arguments are those that do not have a default value assigned.
Required arguments are often called “required positional arguments” because they must be assigned at a particular position in a function call. If you specify an optional argument before a required argument, Python returns an error that looks like this:
positional argument follows keyword argument
This is because if optional arguments came before required arguments then it will eliminate the purpose of optional arguments. How would Python know what values to assign to what arguments if the optional ones came first?
Optional Arguments Python: **kwargs
The **kwargs keyword passes arguments to a function that are assigned to a particular keyword. **kwags represents an aribitrary number of keywords, whether that is zero, one, or more keywords. So, you can use **kwargs to use an optional argument with a function.
Let’s write a program that prints out information about the grades a student has earned on their tests to the console. To start, define a dictionary with some information about a student:
amy = { "Name": "Amy", "Final Assessment": 74, "Second Test": 72, "First Test": 68 }
Our dictionary contains four keys and values. We’re going to write a function that prints out values from this dictionary to the console:
"Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!"
Venus, Software Engineer at Rockbot
def show_grades(student, **grades): print("Student record for {}: ".format(student)) for key, value in grades.items(): print("{} earned a grade of {} in their {}.".format(student, value, key))
This function prints out a message stating “Student record for X”, where X is equal to the name of a student.
Next, our program prints out all the items in the “grades” variable to the console. “grades” uses the “**” syntax which means it contains a dictionary of keys and values over which we can iterate in our program.
Let’s call our function:
show_grades(amy["Name"], SecondTest=amy["Second Test"])
We have specified two arguments: the name of the student and the score they earned on their second test. The second argument needs to have a keyword because **kwargs represents keyword arguments.
Let’s run our code and see if it works:
Student record for Amy: Amy earned a grade of 72 in their SecondTest.
Our program informs us about the grade Amy, a student, earned in their second test. Try to pass another test score through our function as an argument:
show_grades(amy["Name"], FirstTest=amy["First Test"], SecondTest=amy["Second Test"])
Our function now accepts three arguments. The last two arguments are keyword arguments. Let’s run our program:
Student record for Amy: Amy earned a grade of 68 in their FirstTest. Amy earned a grade of 72 in their SecondTest.
Our program shows us the grades that Amy earned in both her first and second test. This is because the **kwargs keyword accepts a variable number of arguments.
Our program also works if we do not specify any keyword arguments:
show_grades(amy["Name"])
Our code returns:
Student record for Amy:
Conclusion
You can define Python function optional arguments by specifying the name of an argument followed by a default value when you declare a function. You can also use the **kwargs method to accept a variable number of arguments in a function.
To learn more about coding in Python, read our How to Learn Python guide.
About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.