Rocket's new status function always prints the same thing: Station 1, online. But Mission Control has twelve stations, and some of them are offline.
"I could write twelve functions," he says, then shakes his head. "No. That is the copy problem all over again."
Raven studies the line inside the function. "What do you notice?" she asks. "Only two parts change: the station number and the status. Everything else stays the same."
Nova draws two empty slots in the function's brackets. "I found a pattern," she says. "Give the function slots for the parts that change. Each call fills them in."
Rocket adds two names between the brackets.
A parameter is a name in the brackets of def. An argument is the value you put in the brackets when you call. When the function runs, each parameter holds its argument.
Arguments match parameters by position: the first argument goes to the first parameter, the second to the second.
# station_status.py
def show_status(station, status):
print(f"Station {station}: {status}")
show_status(1, "online")
show_status(2, "offline")
show_status(3, "online") Station 1: online Station 2: offline Station 3: online
# all_stations.py
def show_status(station, status):
print(f"Station {station}: {status}")
offline = [2, 5]
for number in range(1, 6):
if number in offline:
show_status(number, "offline")
else:
show_status(number, "online") Station 1: online Station 2: offline Station 3: online Station 4: online Station 5: offline
A function body can hold a loop. A parameter can control how many times it goes round.
# countdown_fn.py
def countdown(start):
for n in range(start, 0, -1):
print(n)
print("Go!")
countdown(3)
countdown(2) 3 2 1 Go! 2 1 Go!
| Statement | True or false? |
|---|---|
| A parameter is a name in the def line. | ? |
| An argument is the value given in a call. | ? |
| Arguments fill parameters from right to left. | ? |
| A function can have a loop inside it. | ? |
Parameters make one function useful in many situations. Tomorrow you will learn the difference between printing a result and returning it.