Python Optional Arguments Tutorial

In this section, we will learn what optional arguments are and how to use them in Python.

Note: we’re assuming you’re familiar with functions in Python.

Python Default Arguments (Optional Parameters)

So far, we’ve learned that a function can have zero or more parameters. We also know that when a function is called, we need to pass enough arguments to that function so that its entire parameters are filled with data. Otherwise, if we pass less or more than the parameters of the function, we will get error instead.

But sometimes there’s no input value for a parameter of a function! For example, let’s say there’s a function that takes two parameters `firstName` and `lastName`. But we might face a person that does not have a last name! In that case, a typical function will probably crash because there’s no value for its `lastName` parameter!

This is where Python provided something called the default arguments (AKA optional parameters).

In Python, we’re allowed to set a default value for a parameter when that is being declared. This is known as the default argument or optional parameters.

This means if we called the target function and didn’t pass a value for an optional parameter, that parameter will stick to the default value it had at the declaration time.

Python Optional Arguments Syntax

def functionName(parameter = default_value, parameterN = default_value)

Note: we don’t need to set default value for the entire parameters of a function. The use of default values is optional and so a parameter of a function can have the default value but the other one doesn’t. In a situation like this, those parameters with default value should come as the last parameters and those that do not have default values should put as the first parameters.

Example:

def functionName( parameter1, parameter2, parameter3 = default_value, parameterN = default_Value)

As you can see, the first 3 parameters don’t have default values and for this reason, we put them first. After that we have parameters with default values and so they are declared last in the order of parameters.

Example: declaring optional arguments in python

def printName(firstName = "John", lastName = "Doe"):
    print(f"Hello {firstName} {lastName}")

printName("Jack")

How Does Optional Arguments Work in Python?

In the example above, when we called the `printName()` function, we’ve passed only one argument. This means now the `firstName` parameter has the value `Jack` but the `lastName` parameter will stick to its default value which is `Doe`.

That’s how we got the value `Jack Doe` on the output.

Example: functions and optional arguments

def printName(firstName, lastName = "Doe"):
    print(f"Hello {firstName} {lastName}")

printName("John")

Output:

John Doe
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies