Returning Values
The function print_area you wrote earlier in this lesson prints the area, and that's all. But what if we want to keep calculating with the result, for example add up the areas of all the rooms in an apartment? A printed value is only shown in the output; the program can't work with it anymore.
That's why functions can return a value. The keyword return sends a value back to the place where the function was called:
def add(a, b):
return a + b
result = add(2, 3)
print(result)This prints:
5The call add(2, 3) runs the function, and the function returns 5. You can imagine that Python replaces the call with the value the function returned, so result = add(2, 3) becomes result = 5. The value a function returns is called its return value. You already know some: len(names) returns the number of elements in a list, and .pop() returns the element it removed.
You can use a call anywhere you would write a value: print it straight away, calculate with it, or put it in an f-string or a condition:
def add(a, b):
return a + b
print(add(2, 3))
total = add(2, 3) * 2
print(total)
print(f"2 + 3 = {add(2, 3)}")
if add(2, 3) > 4:
print("More than 4")This prints:
5
10
2 + 3 = 5
More than 4In print(add(2, 3)), Python first calls add(2, 3), and then prints the 5 the function returned. In add(2, 3) * 2, the call becomes 5, and 5 * 2 is 10.
Instructions
The program ends with the error NameError: name 'rectangle_area' is not defined, because the function doesn't exist yet. Write it in place of the comment: the function rectangle_area has two parameters, width and height, and returns width * height. The program then prints Kitchen: 12 and Bedroom: 20.
The apartment also has a living room of 6 × 5 meters. Create a variable living_room with its area, calculated with the function rectangle_area. Then print the area of the whole apartment, kitchen + bedroom + living_room, with the label Whole apartment:. It should be 62.