Python, from Zero, for AI · Chapter 03

Printing and returning are not the same thing

1:44 · Narrated with a synthetic voice. Captions are available in the player.

Read the transcript

Module three is about code you can read again in March. It starts with the single biggest confusion at this stage. Print puts characters on a screen for a person. Return hands a value back to the rest of the program. They look identical when you are testing at a terminal, because in both cases you see twelve. The difference appears the moment you try to use the answer: a function that prints can only ever feed a screen, and a function that returns feeds a file, a test, a request and a screen. A function with no return hands back nothing at all, which is why adding one to it fails. The module then walks through the traps that survive contact with real programs. The most famous is the default argument that is a list. The empty list is created once, when the definition line runs, and every call that does not supply its own gets that same list, with everything the previous calls left in it. The mechanism explains the whole rule: a definition is a statement, and its defaults are evaluated at that moment rather than at call time. The module goes on to scope, why a variable assigned anywhere in a function is local everywhere in it, and how to split a script into modules without breaking the imports.

Sources and further reading (1)