Default and keyword arguments and docstrings
Write functions with default parameter values, call them with positional and keyword arguments, and document them with a docstring that says what goes in and what comes out.
It opens on
total has parameters price, tax and tip, with tax 0.08 and tip 0 unless given. Someone calls total(20, 0.15) meaning a 15% tip. Does it return 24.6, or something else?
Why it matters
Almost every library function, from print to the ones used in data science, has optional parameters set by name, such as print's sep and end; calling them well, and writing functions others can call without reading the body, is everyday programming.
Good to know first
- Defining and calling functions: def, parameters, return and a call
- Scope and the call stack: a call binds each argument to a parameter in its own frame
Step by step
Default values
Write a function with default parameter values and predict which parameter each positional argument binds to.
total(20) binds price to 20, and tax and tip take their defaults, so it returns 20 × 1.08 = 21.6, which the run printed. total(20, 0.05) binds 0.05 to the second parameter, tax, and printed 21.0.
A common mix-up
Python matches a positional argument to the parameter the caller has in mind.
In fact: It matches strictly by position, so the second number always goes to tax.
Keyword arguments
Call a function with keyword arguments, mix them correctly with positional ones, and read the errors of four broken calls.
So it returns 20 × 1.23 = 24.6, the bill the caller in the opening question wanted; the run printed 24.6.
A common mix-up
Keyword arguments can go anywhere in a call.
In fact: All positional arguments must come before the first keyword one, or it is a SyntaxError.
Docstrings
Write a docstring that says what a function takes and what it returns, and read it with help.
help(total) printed the signature with the defaults, then the docstring.
what help(total) printed
A common mix-up
A comment above the function does the same job as a docstring.
In fact: Only the docstring is attached to the function and shown by help and by editors.
Try it
def greet(name, greeting='Hello'): return greeting + ', ' + name + '!' What do greet('Ada') and greet('Ada', 'Hi') return?Answer
Hello, Ada! and Hi, Ada!
Hint: The second argument goes to greeting
What does total(40, tip=0.1) return?Answer
47.2, since 40 × 1.18
Hint: Tax keeps its default
Write the docstring for greet(name, greeting='Hello').Answer
"""Return a greeting such as Hello, Ada! name: the person to greet; greeting: the word to use, Hello by default."""
Hint: Summary, then each parameter
So in total(20, 0.15), which parameter gets 0.15, and what is returned?Answer
Tax, the second parameter, so it returns 20 × 1.15 = 23.0, with tip still 0.
What does total(tip=0.2, price=50) return?Answer
64.0, since price is 50, tax defaults to 0.08 and tip is 0.2, so 50 × 1.28.
