Default Values for Parameters
Learn about parameter defaults and usage in Python functions.
We'll cover the following...
If we want to make a parameter’s value optional, we can specify a default value. Some other languages (Java, for example) require a second method with a different set of parameters. In Python, we define a single method; we can provide a default value for a parameter using an equals sign. If the calling code does not supply an argument value for the parameter, it will be assigned the given default value. This means calling code can still choose to override the default by passing in a different value. If a value of None
is used as the default for optional parameter values, the typing
module lets us describe this using the Optional
type hint.
Here’s a function definition with default parameter definitions:
def latitude_dms(deg: float, min: float, sec: float = 0.0, dir: Optional[str] = None) -> strif dir is None:dir = "N"return f"{deg:02.0f}° {min+sec/60:05.3f}{dir}"
The first two parameters are mandatory and must be provided. The last two parameters have default argument values and can be omitted.
There are several ways we can call this function. We can supply all argument values in order, as though all the parameters were positional, as can be seen in the following:
from typing import Optionaldef latitude_dms(deg: float, min: float, sec: float = 0.0, dir: Optional[str] = None) -> str:if dir is None:dir = "N"return f"{deg:02.0f}° {min+sec/60:05.3f}{dir}"print(latitude_dms(36, 51, 2.9, "N"))
Alternatively, we can supply just the mandatory argument values in order, allowing one of the keyword parameters (sec
) to use a default value, and providing a keyword argument for the dir
parameter:
from typing import Optionaldef latitude_dms(deg: float, min: float, sec: float = 0.0, dir: Optional[str] = None) -> str:if dir is None:dir = "N"return f"{deg:02.0f}° {min+sec/60:05.3f}{dir}"print(latitude_dms(38, 58, dir = "N"))
We’ve used equals sign syntax when calling a function to skip default values that we aren’t interested in.
Surprisingly, we can even use ...