Browser lab18 min+60 XP

Return values

Functions that hand back an answer you can store, print or use in more maths.

0% done

Code runs right here in your browser. Nothing to install.

TASK 1

Learn it

Key idea

return hands a value back so you can store it. print only shows it.

Key words
area(4, 5)return 20hands the value backroom = area(4, 5)stored: use it againshow_area(4, 5)print(20)shows it on screenScreen shows 20value is gone
A returned value can be stored and reused. A printed value cannot.

print() shows something on screen, but your program cannot use it afterwards. return sends a value back to the code that called the function, so you can store it in a variable or use it in a calculation.

When Python reaches return, the function stops immediately and hands back the value. A function with no return gives back the special value None.

Think of it like a vending machine: you put in arguments, and it returns a snack you can do whatever you like with.

Real life linkA calculator does not shout the answer and forget it. It hands the answer back so you can use it in the next sum. That is a return value.
Example code
def area(width, height):
    return width * height

room = area(4, 5)
garden = area(10, 3)
print("Room:", room)
print("Total:", room + garden)
TASK 2

Try it yourself

+10 XP

Write double(n) that returns n times 2 (no printing inside the function). Then print double(21) and double(double(5)).

Create a free account to start this lab

Sign in to write, run and check your code here. Your progress, XP and code are saved to your account. No card needed.

TASK 3

Capture the flag

+10 XP

What value does a function give back if it has no return statement?

Create a free account to start this lab

Sign in to answer the flag question. Your progress, XP and code are saved to your account. No card needed.

HOMEWORK

Shape calculator

+20 XP

Write three functions that return values: rect_area(w, h), triangle_area(b, h) (half of base times height) and circle_area(r) (use 3.14159 * r * r). Print each for (4, 5), (6, 3) and radius 2, rounded to 2 decimal places.

Create a free account to start this lab

Sign in to do this homework and have it checked. Your progress, XP and code are saved to your account. No card needed.