Python language basics 30: providing default values to a function
July 18, 2015 Leave a comment
Introduction
In the previous post we looked at how objects are passed by reference to function in Python. We saw how it could be dangerous to let a function modify an incoming parameter if you’re not aware of the reference passing behaviour. We also briefly looked at the idea of a deep copy which is one way to keep your original objects intact.
In this post we’ll diverge from objects and instead investigate a feature of functions: default arguments.
Default arguments are simply provided by the assignment operator ‘=’ in the arguments list:
def multiply(base, multiplier=2, show_greeting=True): if show_greeting: print("Welcome to the multiply function") return base * multiplier
The above function has one compulsory arguments and 2 optional ones. If you omit the ‘multiplier’ and ‘show_greeting’ arguments then their default values 2 and True will be used in the multiply function:
result = multiply(10)
‘result’ will be 20 and the greeting will be printed in the output window. You can override the default values by simply passing in the values for those arguments:
result = multiply(10, 3, False)
‘result’ will be 30 and the greeting won’t be shown.
Note that default arguments must be given last in the argument list. The following won’t work:
def multiply(multiplier=2, base, show_greeting=True):
You’ll get an error saying that a non-default argument follows a default one.
In the next post we’ll look at positional and keyword arguments to a Python function.
Read all Python-related posts on this blog here.