Each hop between stars takes the fleet 3 hours. Rocket keeps working out trip times by hand.
"Four hops is 12 hours. Two hops is 6 hours. Seven hops is," he pauses. "I keep doing the same math!"
Raven asks, "What do you notice about every trip?"
"It is always hops times 3," Rocket says.
Nova glows. "Here is a hint. Write the math once in a function, and let it return the answer."
def makes a function. The name in the brackets is a parameter. It holds the value you pass in.
return hands a value back to the line that called the function. That line can store it or print it.
def trip_hours(hops):
return hops * 3
a = trip_hours(4)
b = trip_hours(2)
print(a + b) Output: 18
trip_hours(4) returns 12 and trip_hours(2) returns 6. Then 12 plus 6 is 18.
A function that only prints shows a value on the screen. It does not hand anything back. Python then gives back None, which means no value.
def show_hours(hops):
print(hops * 3)
x = show_hours(2)
print(x) def most(a, b):
if a > b:
return a
return ____
print(most(3, 8)) def fuel_for(hops):
return hops * 4 + 2
def can_go(tank, hops):
return tank >= fuel_for(hops)
print(fuel_for(3))
print(can_go(14, 3))
print(can_go(13, 3)) | Statement | True or false? |
|---|---|
| fuel_for(1) returns 6. | ? |
| can_go(22, 5) returns True. | ? |
| return shows the value on the screen. | ? |
| A function can be called inside another function. | ? |
Week 1 done, Crew Engineer! Lists, loops, choices, dictionaries and functions are all back in your toolkit. Next week, functions start calling other functions.