Grade 7 Computer Science · Functions
A function — a name for a passage of code
Defining once, calling from several places, and thinking in larger terms.
Thirty lines, and nothing happened
Thirty lines, no typos and no error message — and the screen stays blank. The code is perfectly fine. What is missing is one short line, and the difference between it and all the rest is the difference between teaching and doing.
In the unit on variables we gave a name to a value. Now we shall give a name to a whole passage of code. That sounds like a small idea, and it is the idea that makes it possible to write programs larger than can be held in one’s head — which is nearly every real program.
def greet():
print("Hello")
print("Welcome")
greet()
greet()| The action | What happens |
|---|---|
| Defining | The computer learns; no line runs |
| Calling | The passage is carried out from its start |
A good name makes the code readable
A function’s advantage is not only saving duplication. It is that it gives a passage of code a name, and once there is a name one can think in its terms rather than in terms of the lines. A program that calls compute-average and then print-report is readable to someone who did not write it, without even looking inside. This is the same idea seen in variable names, now at a higher level: a good name is documentation you cannot forget to update.
Example 1 — why “nothing happened”
- The function was defined at the top of the file.
- But no line calls it.
- So no line inside it ran.
- The fix is one calling line.
Example 2 — one definition, two calls
- The function prints two lines.
- It is called a first time — two lines.
- It is called again — two more.
- Four in all, from a passage written once.