The fuel function needs three numbers: the distance, the burn rate and a safety reserve. Almost every trip uses a rate of 3 and a reserve of 10, and Rocket is tired of typing them.
"Ninety percent of the time it is the same numbers," he says. "Can the function just remember them?"
Raven flips through her notes from a month ago. "What do you notice?" she asks. "We also forgot what this function was for. There is no note telling us."
Nova displays the function with two glowing default values and a short sentence underneath. "Would you like a hint?" she asks. "Parameters can have defaults. And a function can describe itself."
Rocket fixes both problems in two lines.
A parameter can have a default, written with = in the def line. If the call leaves that argument out, the default is used. Parameters with defaults go after the ones without.
You can also name an argument when you call, like reserve=0. That is a keyword argument. It lets you skip the ones in the middle.
# fuel_needed.py
def fuel_needed(distance, rate=3, reserve=10):
"""Fuel for a trip: distance times rate, plus a reserve."""
return distance * rate + reserve
print(fuel_needed(20))
print(fuel_needed(20, 4))
print(fuel_needed(20, reserve=0)) 70 90 60
| Call | distance | rate | reserve | Result |
|---|---|---|---|---|
| fuel_needed(20) | 20 | 3 (default) | 10 (default) | 70 |
| fuel_needed(20, 4) | 20 | 4 | 10 (default) | 90 |
| fuel_needed(20, reserve=0) | 20 | 3 (default) | 0 | 60 |
The line in triple quotes right under def is a docstring. It says what the function does. Unlike a comment, Python keeps it, and help() shows it.
Try help(fuel_needed) in the shell after running the file. You will see the def line and the docstring.
Defaults work for strings too. Here the greeting has a default, but a caller can still choose a different one.
# greet.py
def greet(call_sign, greeting="Welcome aboard"):
"""Make a greeting for a crew call sign."""
return f"{greeting}, {call_sign}!"
print(greet("Comet"))
print(greet("Pathfinder", "Good morning"))
print(greet(greeting="Hello", call_sign="Nova")) Welcome aboard, Comet! Good morning, Pathfinder! Hello, Nova!
| Statement | True or false? |
|---|---|
| A docstring goes in triple quotes under the def line. | ? |
| help() can show a function's docstring. | ? |
| A default is used even when the caller gives that argument. | ? |
| Keyword arguments let you pass values by name. | ? |
Defaults keep calls short, and docstrings keep your future self informed. Tomorrow you will move your functions into a module of your own.