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. ...
Get Python Essentials now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.