Rocket wrote a function that turns hours into minutes. It prints the answer nicely. But now he needs to add two trips together, and the function will not give him a number to add.
"It prints 150," he says, puzzled. "I can see it right there. Why is my total None?"
Raven reads the function slowly. "What do you notice?" she asks. "It shows the answer on the screen. It never hands the answer back to the line that called it."
Nova holds out a small glowing parcel. "Interesting," she says. "Printing is for people. Returning is for the program. A function hands back a value with return."
Rocket swaps one word in his function and the total appears.
return ends the function and hands a value back to the line that called it. That value can be stored, printed or used in more math.
print only shows something on the screen. A function without return hands back None.
# minutes.py
def to_minutes(hours):
return hours * 60
trip = to_minutes(2.5)
print("Trip minutes:", trip)
print("Two trips:", to_minutes(1) + to_minutes(2)) Trip minutes: 150.0 Two trips: 180
2.5 is a float, so the answer is the float 150.0. The whole numbers 1 and 2 give whole answers, 60 and 120.
# print_not_return.py
def double_print(n):
print(n * 2)
result = double_print(4)
print("result is", result) 8 result is None
A function can return a bool. Then its call reads like a question inside an if, such as if is_safe(85, 20):.
# is_safe.py
def is_safe(fuel, wind):
return fuel >= 80 and wind < 30
print(is_safe(90, 10))
print(is_safe(90, 45))
if is_safe(85, 20):
print("Launch window open") | Statement | True or false? |
|---|---|
| return ends the function straight away. | ? |
| A function without return hands back None. | ? |
| print and return do exactly the same job. | ? |
| A returned bool can be used as an if condition. | ? |
Return values let functions build on each other like parts of a machine. Tomorrow you will give parameters default values.