Why Name a Piece of Work
As scripts grow, the same few lines start to appear in several places. Then one day you fix a mistake in one copy, forget the others, and the program starts disagreeing with itself. A function solves this by giving a piece of work a name. You write it once and use it by name wherever it is needed, and when it needs fixing there is exactly one place to fix.
Think of a recipe card called "make the sauce". A cookbook does not reprint the sauce steps inside every dish that uses the sauce; it says "make the sauce" and you turn to that card. The card is the function, and the dish that says its name is calling it.
The Copy-Paste Problem
Here is a script that converts three temperatures from Celsius to Fahrenheit. The formula is multiply by nine, divide by five, add thirty-two. It was pasted three times, and the third copy was mistyped as plus twenty-three. The output looks plausible, which is exactly what makes this kind of bug dangerous.
morning = 12 noon = 25 evening = 18 print(morning * 9 / 5 + 32) print(noon * 9 / 5 + 32) print(evening * 9 / 5 + 23)
53.6 77.0 55.4
def Gives Work a Name
The word def, short for define, creates a function. After it comes the function's name, brackets, and a colon; the indented block beneath is the function's body. The version below defines to_fahrenheit once, with the formula in one place, and uses it three times. The value in the brackets is handed to the function, and the word return hands the result back out; both are the subject of the next topic.
def to_fahrenheit(celsius): return celsius * 9 / 5 + 32 print(to_fahrenheit(12)) print(to_fahrenheit(25)) print(to_fahrenheit(18))
53.6 77.0 64.4
The third answer is now right, 64.4, because every conversion goes through the same formula. If the formula were wrong, all three answers would be wrong together, which is far easier to notice, and there would be one line to fix.
Defining Is Not Running
A def block does not do anything by itself. It creates the function and gives it a name, like writing a recipe card and putting it in the drawer. The body runs only when something calls the function, by writing its name followed by brackets. A file containing only a def runs without error and prints nothing at all.
def greet(): print("Hello from inside a function.")
Add a call on the last line, greet(), and the message appears. Without the brackets, greet on its own only names the function; it does not run it.
def greet(): print("Hello from inside a function.") greet()
Hello from inside a function.
Functions You Already Know
You have been calling functions since Chapter 1: print, len, input, int, sum. Someone else wrote them, and you use them by name without ever seeing their bodies. Writing your own functions puts you on the other side of that arrangement.
- "Writing def runs the code." It only defines the function. The body runs each time the function is called.
- "
greetandgreet()mean the same." Without brackets you are naming the function; with brackets you are running it. - "Functions are only for big programs." Any piece of work you use twice, or that deserves a name, is worth a function, even in a ten-line script.
- One place to fix is the difference between a script you can maintain and one you end up rewriting.
- Naming a piece of work makes the rest of the program read like a list of steps, which is how other people will read your code.
Knowledge Check
What happens when Python reads a def block?
- It creates the function and waits for a call
- It runs the body once to check that it works
- It runs the body and then deletes the function
- It prints the function's name in the terminal
What is the difference between greet and greet()?
- None: brackets are optional when nothing goes in
greet()runs the function;greetonly names itgreetruns it quickly, andgreet()runs it fullygreet()defines the function, andgreetruns it
What problem does the copy-paste example show?
- Formulas with decimals cannot be pasted into a program
- Python refuses to run the same formula more than twice
- Copies drift apart, and a mistake hides in one of them
- The output of the program was printed in the wrong order
A file contains only a def block. What happens when you run it?
- Python raises an error because the function is unused
- Python runs the function's body once automatically
- Python asks which function you would like to run
- Nothing is printed; the function is defined and not called
You got correct