Getting answers back: what return does
Some recipes do a job. Others work out an answer. return is how a recipe hands its answer back to the line that asked.
The big idea
return sends a value out of a function, back to the place that called it, so the rest of your program can use it.
See it in code
This recipe works out a price and returns it. The call then stands in for the answer, so you can store it in a variable:
cookie_price = 3
def price_of(how_many):
return how_many * cookie_price
total = price_of(4)
print("Total: $", total)Total: $ 12
price_of(4) became 12. The recipe didn't print anything itself. It handed the number back and let the caller decide what to do with it.
Printing is not the same as returning. A recipe with no return hands back a special value called None, which means "nothing":
box_size = 6
def loud_boxes(how_many):
print(how_many // box_size)
def box_count(how_many):
return how_many // box_size
answer = loud_boxes(18)
print("The loud recipe handed back:", answer)
answer = box_count(18)
print("The quiet recipe handed back:", answer)3 The loud recipe handed back: None The quiet recipe handed back: 3
The loud recipe showed 3 on the screen, then handed back None. The quiet one handed back a real 3 that other code can use.
A recipe can return a color. Each window calls window_color(), and each call makes its own choice: usually lit, sometimes dark:
lit_colors = ["gold", "light yellow", "orange"]
dark_odds = 3
floors = 8
floor_height = 36
street_top = 360
def window_color():
if random_number(1, dark_odds) == 1:
return "black"
return pick(lit_colors)
paper("midnight blue")
rect(x=200, y=380, width=400, height=40, color="black")
rect(x=200, y=street_top - floors * floor_height / 2, width=150, height=floors * floor_height, color="slate gray")
for floor in range(floors):
window_y = street_top - 18 - floor * floor_height
for window_x in [150, 183, 217, 250]:
square(x=window_x, y=window_y, size=18, color=window_color())
return also ends the recipe right away. When the first return runs, the second one is never reached. That's why a window is black or lit, never both.
Returning is how recipes work together. One returns a price, another uses that price to build a receipt line, and a third adds the lines up.
Try it yourself
Change dark_odds = 3 to dark_odds = 2 and run it. More windows go dark. Then add a color to lit_colors. The recipe's answers change, and no other line needs editing.
The common mistake
Using print when other code needs the answer. If price_of printed instead of returning, total would hold None and your math would break. Use return whenever the answer is needed later.
What it unlocks
Returning makes functions fit together like building blocks. A recipe that returns a price pairs well with a dictionary of price tags, and with a running total.