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."
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
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)) 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)))) | Statement | True 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. | ? |
Excellent! A return always goes back to whoever called. Tomorrow we use helpers to build a fuel check, and catch a sneaky bug.