return: Handing a Value Back

This is the distinction that unlocks everything.

print displays something to a human and hands nothing back to the program.

return hands a value back to the code that called the function, so you can store it, compare it, or feed it into another function.

A function that prints is a dead end. A function that returns is a building block.

Returning a value

PYTHON

def square(number):
    return number ** 2

result = square(5)
print(result)
print(square(3) + square(4))

JAVASCRIPT

function square(number) {
  return number ** 2;
}

const result = square(5);
console.log(result);
console.log(square(3) + square(4)); 
Compare → Identical keyword, identical behavior. Because square RETURNS, its result can be stored in a variable and even added to another call's result. A printing version could do neither.
EXAMPLE
loading editor…
YOUR TURN
Your turn → square(3) + square(4) is 25, the same as square(5), a famous coincidence. Write a cube function that returns its number to the power of 3, and print cube(2) + cube(3).
loading editor…

Syntax has to be exact. Every quote, bracket and parenthesis needs its partner, and in Python the spaces at the start of a line count. One slip and the program won't run; the message will say where.

✦ return exits immediately

The moment return runs, the function stops, any lines after it are never reached. That's useful: an early return can handle a special case up front and skip the rest. A function with no return statement gives back None in Python and undefined in JavaScript.

EXAMPLE
loading editor…
YOUR TURN
Your turn → Add a case so describe returns "big" for numbers over 100, then test it with 250.
loading editor…

Syntax has to be exact. Every quote, bracket and parenthesis needs its partner, and in Python the spaces at the start of a line count. One slip and the program won't run; the message will say where.

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Functions Over Collections →
← Back