Raven needs to double the fuel number for a round trip. Rocket's double function prints the answer on the screen. "Great," Raven says. "Now add 5 for safety."
Rocket stares at the screen. The answer is just sitting there. He cannot add anything to it.
"What do you notice?" Raven asks. "Printing shows a number to us. But the program cannot use it." Nova tosses a glowing ball back to Rocket. "Would you like a hint? A function can hand its answer back."
return sends a value back to the line that called the function.
The call then stands for that value. You can store it, print it or do math with it.
def double(n):
return n * 2
x = double(4)
print(x)
print(double(10) + 5) | The screen shows |
|---|
| 8 |
| 25 |
| return | |
|---|---|
| shows a value on the screen | hands a value back to the program |
| the program cannot use it after | the program can store it or do math with it |
def double(n):
return n * 2
print(double(double(3))) def add_safety(units):
return units + 5
def round_trip(units):
return units * 2
trip = round_trip(20)
trip = add_safety(trip)
print(trip) | Statement | True or false? |
|---|---|
| return shows the value on the screen. | ? |
| A call to a function that returns can be stored in a variable. | ? |
| return n * 2 sends back twice n. | ? |
def triple(n):
return n * 3
a = triple(2)
b = triple(a)
print(a, b)
print(triple(1) + triple(4)) | Statement | True or false? |
|---|---|
| return sends the value back to the call. | ? |
| You can do math with a returned value. | ? |
| print and return do the same job. | ? |
| triple(2) gives 6. | ? |
You can make functions that answer! Tomorrow you will build the fuel budget with them.