Master Python

First steps

11 / 253
Contents

Contents

Master Python

0 of 253 complete

6 min read

print and return are not the same thing

The difference that trips almost everybody up once, and how the problems at the end of a section are marked.

There are now two ways to get something out of a function, and they look far more alike than they are. One shows a value to a person reading the screen. The other hands the value back to whatever asked for it. Almost everybody confuses the two at least once, so it is worth a lesson of its own.

print shows a value to a person. return hands a value back to the program. When you are testing by eye they look similar, and they are completely different.

Both functions here have empty brackets, which is allowed: a function does not have to be handed anything, and shout() needs nothing in order to shout. The brackets still have to be there, both when the function is described and when it is called.

Try CodePython

Run it and look carefully at the three lines of output, especially the middle one. Then change print(shout()) to just shout() and run it again.

shout wrote its message and handed nothing back. Python's word for nothing is None, and that is what the surrounding print then dutifully wrote out on the second line. hand_back handed its message back instead, so print had something real to write.

That last point is worth taking seriously. A solution that prints the right answer and returns nothing scores zero, which feels harsh until you remember the vending machine that shouts the name of your drink across the room and keeps it.

What a problem looks like

  1. You are given a starting point: the first line of the function, already written, with the parameters named. Leave that line as it is, because the marker, the software that runs your function against the tests and checks what comes back, calls it by that name.
  2. You write the body, ending in a return.
  3. Press run to check your answer against the visible tests. Each one shows what was handed in, what you gave back, and what was wanted.
  4. Press submit to check it against the hidden tests as well. Those are the awkward cases: an empty piece of text, a zero, a negative number. They are hidden so that an answer which only works on the examples does not slip through.
What is the difference between a function whose body is print(number * 2) and one whose body is return number * 2?

The first works out the doubled number, writes it on the screen, and hands nothing back, so whatever called it receives None. The second hands the doubled number back and writes nothing on the screen. You can do both, on two lines, if you want to watch what your function is doing while you work on it, but the marker only ever looks at what you return.

All lessons in Master Python