3. Return

return ends the function and sends a value back to the caller. The call expression then evaluates to that value:

  • return expression computes the expression and gives the result back.
  • Code after return in the same branch does not run.
  • A function without return gives back None.
  • print() shows text in the console; return gives a value to the caller. They are not the same thing.
#01

Return a value

Define double(n) that returns n * 2. Do not print inside the function. Call it inside print() with the argument 5.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#02

Store the returned value

Define square(n) that returns n * n. Store the result of square(3) in a variable named result, then print result.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#03

A function without return gives None

Define say_hi() that prints Hi and has no return. Then print the result of calling say_hi().

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#04

Use the returned value in an expression

Define double(n) that returns n * 2. Print double(3) + 1 directly, without storing the result first.

Print exactly:

Create a free account to save your progress and unlock chapter 2.