Writing Your Own Functions · practice
Return a Value
Some
You have already used that second kind:
letter_count = len("Python")
len("Python") produces the integer 6, and the letter_count.
Your own functions can produce values with
def double(number):
return number * 2
The function call now has a value:
result = double(7)
print(result)
The 7 becomes the number. The number * 2 produces 14. Then return sends 14 back to the caller, where it is assigned to result.
A call can be used as an expression
Because double(7) returns a value, you can use the call anywhere that value would make sense:
Assigning the result to a
Return ends the call
When Python reaches return, it immediately sends the value back to the caller. Lines later in that function body do not run:
def double(number):
return number * 2
print("This line is unreachable.")
For now, put the main calculation in one return near the end of a small function. Later chapters will show situations where an earlier return makes sense.
Return information, then decide how to use it
Here is a function that builds text without deciding where that text should go:
def make_label(name, place):
return f"{name} -> {place}"
One caller can print the label:
print(make_label("Iris", "Oslo"))
Another can store it:
first_trip = make_label("Iris", "Oslo")
Another can put it in a
trips = [make_label("Iris", "Oslo"), make_label("Dev", "Accra")]
The function stays useful because it returns the result instead of making every later decision itself.
What does this program print?
def add_fee(price):
return price + 3
total = add_fee(7)
print(total * 2)
Task
Complete make_label(name, place) so it returns a trip label in this form:
Iris -> Oslo
Then keep the existing print call so the program displays the returned label once.
Expected output:
Iris -> Oslo
After it passes, use Step in the exercise editor. Watch Python enter make_label, reach label.