Hone

Lessons · Python · showing a value or handing it back

Showing a value versus giving it back

print writes to the screen and gives the caller nothing; return hands the value to whoever called the function.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

Every function another piece of code uses must return. A function that prints the answer is a dead end: nobody can total it, save it, or test it.

How to think about it

Ask: who needs this value next? A person looking at a screen: print. Another line of code: return. When in doubt, return; the caller can always print.

Worked example

def triple(n):
A function that should give a value back.
    return n * 3
Hands 3n to the caller.
x = triple(4)
x is 12, usable.
print(x + 1)
9. Printing is the caller's choice.

Your turn

Make the function usable by other code.

def area(w, h):
     w * h

The trap

A function with print and no return gives None. Then x = f(3) makes x None, and the crash happens later, somewhere else.

Practise showing a value or handing it back on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.