Return Ends the Function
return does two things at once: it gives a value back, and it ends the function immediately. The rest of the function doesn't run:
def add(a, b):
return a + b
print("This line never runs.")
print(add(2, 3))This prints:
5The line after return never runs, because the function ended one line earlier.
This is handy together with conditions. The following function describes the weather based on the temperature:
def describe_weather(degrees):
if degrees < 0:
return "freezing"
if degrees < 20:
return "cool"
return "warm"
print(describe_weather(-5))
print(describe_weather(12))
print(describe_weather(25))This prints:
freezing
cool
warmLet's follow the three calls:
describe_weather(-5):-5 < 0isTrue, so the function returns"freezing"and ends. The second condition is never checked.describe_weather(12): the first condition isFalseand the second one isTrue, so the function returns"cool".describe_weather(25): neither condition isTrue, so the function gets all the way to the last line and returns"warm".
We didn't need any elif or else: once a return runs, the rest of the function is skipped anyway. (With elif and else, the function would work the same.) But the order of the conditions matters, because the first return that runs wins. If the function checked degrees < 20 first, it would return "cool" for -5, since -5 is less than 20 too.
Instructions
The function ticket_price returns the price of a zoo ticket for a visitor of the given age. For now, it returns 10 for everyone. Above the line return 10, add conditions: children under 6 go free (0), and visitors under 18 pay 5. The program then prints 0, 5 and 10.
Seniors aged 65 and over pay 5 too. Add a condition for them to the function, and at the end of the program, print ticket_price(70).
Start programming for free
7/10