Rocket is planning probe trips to the far edge of the cluster. Every probe must fly out and come back.
"Last week we wrote trip_hours," Rocket says. "Now I need round trips. Should I copy the math into a new function?"
Raven reads the old function. "What do you notice? Half of the new job is already done."
Rocket blinks. "The trip out is trip_hours. The trip back is the same."
Nova twirls. "Here is a hint. A function can use another function, just like you can."
A function can call another function in its own code. The second function does part of the work.
We call the small one a helper function. The bigger function uses the value the helper returns.
def trip_hours(hops):
return hops * 3
def round_trip(hops):
return trip_hours(hops) * 2
print(round_trip(4)) Output: 24
def hours(hops):
return hops * 3
def with_rest(hops):
return hours(hops) + 2
def full_day(hops):
return with_rest(hops) * 2
print(with_rest(4))
print(full_day(1)) | Statement | True or false? |
|---|---|
| full_day calls with_rest. | ? |
| hours calls full_day. | ? |
| with_rest waits for hours to return. | ? |
| Changing hours changes what full_day returns. | ? |
Great thinking! Reusing a helper saves work and avoids copying mistakes. Tomorrow we watch exactly who waits for whom.