← Back to course
Code Crew G5 / Week 02 / Monday
1/6
Week 02 Β· Functions call functions

Monday

One function calls another
// Who waits, who returns
⏱ about 15 min

Monday: One function calls another

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 inside a function

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
  1. The last line calls round_trip(4).
  2. round_trip needs trip_hours(4), so it calls it and waits.
  3. trip_hours returns 4 times 3, which is 12.
  4. round_trip gets 12 and returns 12 times 2, which is 24.
  5. print shows 24.
What would print(round_trip(5)) show?
WHY THIS EXERCISEround_trip uses the value its helper returns, then does its own step.
PUT THE EVENTS OF PRINT(ROUND_TRIP(2)) IN ORDER.
  • ?round_trip(2) starts
  • ?trip_hours returns 6
  • ?print shows 12
  • ?round_trip returns 12
  • ?round_trip calls trip_hours(2)
WHY THIS EXERCISEThe caller pauses while the helper runs, then continues with the returned value.
WHICH FUNCTION DOES EACH JOB?
  • Read the question.
  • Tap your answer.
Which function multiplies by 3?
Which function finishes last?

Practice lab: three helpers deep

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))
What does hours(4) return?
What does with_rest(4) return?
What does full_day(1) return?
How many functions run for full_day(1)?
HELPER CHECK
  • Read the question.
  • Tap your answer.
Which function does with_rest call?
For full_day(1), which function finishes first?
What is a helper function?
StatementTrue 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.?
WHY THIS EXERCISEA change in a helper flows up to every function that uses it.
What does full_day(2) return?
WHY THIS EXERCISEEach step uses the value from the step below it.

Great thinking! Reusing a helper saves work and avoids copying mistakes. Tomorrow we watch exactly who waits for whom.