Exercises
Return Values
3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.
Exercise 1Passed
Return both the smallest and largest number, and unpack them into low and high.
Python
def min_max(numbers):
# return both
pass
# unpack and print
A comma between two values makes a tuple.
def min_max(numbers):
return min(numbers), max(numbers)
low, high = min_max([3, 1, 4])
print(low, high)Exercise 2Passed
Rewrite price_for with early returns rather than nested branches.
Python
def price_for(age):
if age < 16:
return 0
else:
if age >= 65:
return 5
else:
return 12
for age in [10, 30, 70]:
print(price_for(age))Return as soon as you know the answer.
def price_for(age):
if age < 16:
return 0
if age >= 65:
return 5
return 12
for age in [10, 30, 70]:
print(price_for(age))Exercise 3Passed
Return a function that multiplies by the given factor.
Python
def multiplier(factor):
# return a function
pass
triple = multiplier(3)
print(triple(5))Define a function inside and return it without brackets.
def multiplier(factor):
def multiply(n):
return n * factor
return multiply
triple = multiplier(3)
print(triple(5))