Chapter Five · Naming a Piece of Work
Functions
A function gives a piece of work a name, so it is written once and used anywhere. This chapter covers why that matters, how values go into a function and come back out, where the names inside a function live, and how to turn a script that grew top to bottom into a handful of small, named jobs.
By now your programs can hold values, make decisions and repeat work. They can also start to sprawl: the same few lines pasted in three places, a hundred lines with no obvious beginning, middle or end. Functions are the cure. They are also the point where your code starts to look like the Python you will read in other people's projects.
Four topics. Why naming a piece of work pays off, and the difference between defining a function and running it. Parameters, which carry values in, and return, which carries a result out, together with the most common mix-up beginners make with functions. Scope: the rule that names created inside a function stay inside it. And a before-and-after: the tip calculator from earlier chapters, reorganised into small functions with a main.
Topics in This Chapter
def as a way to name a piece of work, and the difference between defining a function and calling it.print is not return.main that tells the story, with docstrings for the people who read it.