← Back to course
Code Crew G5 / Week 01 / Friday
5/6
Week 01 Β· Crew check

Friday

Functions that return
// The tools you already have
⏱ about 15 min

Friday: Functions that return

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, parameters and return

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.

What would print(trip_hours(5)) show?
WHY THIS EXERCISEThe value you pass in becomes the parameter, and return sends the answer back.

print is not return

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)
PREDICT THE OUTPUT OF THE PROGRAM ABOVE.
  • Read the question.
  • Tap your answer.
What is the first line of output?
What is the second line of output?
def most(a, b):
    if a > b:
        return a
    return ____

print(most(3, 8))
FILL THE BLANK SO MOST() RETURNS THE BIGGER NUMBER. THEN PRINT(MOST(3, 8)) SHOWS 8.
  • Read the question.
  • Tap your answer.
What goes in the blank?
At the computer
A grown-up can install Python from python.org. It comes with a simple editor called IDLE.
Type trip_hours into IDLE and run it. Try your own number of hops.
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))
What does fuel_for(3) return?
What does fuel_for(5) return?
What does can_go(13, 3) return?
RETURN CHECK
  • Read the question.
  • Tap your answer.
What kind of value does can_go return?
What does fuel_for(0) return?
Which function calls the other?
StatementTrue 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.?
WHY THIS EXERCISESmall functions combine into bigger ones.
What is the smallest tank that makes can_go(tank, 4) True?
WHY THIS EXERCISEfuel_for(4) is 18, and 18 >= 18 is True.

Week 1 done, Crew Engineer! Lists, loops, choices, dictionaries and functions are all back in your toolkit. Next week, functions start calling other functions.

← Thursday