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

Thursday

Who returns to whom
// Who waits, who returns
⏱ about 15 min

Thursday: Who returns to whom

Nova is mapping two square sectors of the cluster. One is 2 light units on a side. The other is 3.

"I need the total area," says Rocket. "Square both sides and add them."

He writes one long line of code. "add(square(2), square(3)). But which part runs first?"

Raven studies the line. "What do you notice about the brackets?"

Nova draws a circle around the inside parts. "Here is a hint. Python works from the inside out."

Inside out

When a call is inside the brackets of another call, Python runs the inside call first.

Each return value goes back to the exact spot that asked for it. Then the outer call can run.

def square(n):
    return n * n

def add(a, b):
    return a + b

total = add(square(2), square(3))
print(total)
Output:
13
  1. square(2) runs and returns 4 to the first spot.
  2. square(3) runs and returns 9 to the second spot.
  3. Now the line is like add(4, 9).
  4. add returns 13, and total stores it.
For add(square(1), square(4)), what does square(4) return?
What does the whole line add(square(1), square(4)) return?

A chain of returns

def square(n):
    return n * n

def sector_area(side):
    return square(side)

def map_area(a, b):
    return sector_area(a) + sector_area(b)

print(map_area(3, 5))
FOLLOW THE RETURNS IN THE PROGRAM ABOVE.
  • Read the question.
  • Tap your answer.
square returns its value to which function?
What does the program print?

Practice lab: calls in calls

def double(n):
    return n * 2

def plus(a, b):
    return a + b

print(plus(double(3), double(4)))
print(double(plus(1, 2)))
print(double(double(double(1))))
What does line 7 show?
What does line 8 show?
What does line 9 show?
INSIDE OUT
  • Read the question.
  • Tap your answer.
In plus(double(3), double(4)), what runs first?
double(3) returns its value to where?
What is double(plus(5, 5))?
StatementTrue or false?
Inside calls run before the outer call.?
plus(2, 3) returns 6.?
double(plus(1, 2)) is the same as double(3).?
A return value can go straight into another call.?
WHY THIS EXERCISEEvery call stands for the value it returns.
What is plus(double(10), 1)?
WHY THIS EXERCISEThe inner call returns 20 into the first spot of plus.

Excellent! A return always goes back to whoever called. Tomorrow we use helpers to build a fuel check, and catch a sneaky bug.

← Wednesday