Defining optional parameters via default values
Python lets us provide a default value for a parameter. Parameters with default values are optional. The standard library is full of functions with optional parameters. One example is the int()
function. We can use int("48897")
to convert a string to an integer, assuming that the string represents a number in base 10. We can use int("48897", 16)
to explicitly state that the string should be treated as a hexadecimal value. The default value for the base
parameter is 10.
Remember that we can use keyword arguments for a function. This means that we might want to write something like this: int("48897", base=16)
, to make it abundantly clear what the second argument to the int()
function is being used for.
Earlier, we listed two rules for matching argument values to parameters. When we introduce default values, we add two more rules.
Match all positional arguments to parameters from left-to-right.
Match all keyword parameters. In case of already-assigned...