Python: Functions with Optional & Named Arguments
Python allows functions to have default values for arguments. These are used when the function is called without the argument. But where it gets really interesting is when you realize that in Python it’s also possible to name the arguments and call them in any order, which can be very useful.
def shirt(styleID, size='Medium', color='White'): ...
For example, in the ‘shirt’ function above, style is a required argument (since it has no default value) but the other two arguments i.e. size and color are optional (since they do have default values assigned).
There are several ways to call this function:
styleID gets a value of 1 and size and color are assigned their default values.
styleID gets a value of 1 and size gets a value of “Large”, while color gets the default value.
styleID gets a value of 1 and color gets a value of “Black”, while size gets the default value.
size gets a value of “Small” and styleID gets a value of 2, while color gets the default value.