Programs with Structure

Procedures, and calling them

Read a program that gives a block of lines a name, and say what runs, when, and how many times.

Once a program is more than a few lines long, the same handful of lines start turning up in several places, and copying them about is how programs get long and wrong at the same time. A procedure fixes that. You write the lines once, under a heading that gives them a name, and afterwards the name stands for the whole block. Writing the heading and its block is called defining the procedure, and it is worth being clear that defining does not run anything: it puts the lines aside under a name and moves on. To make them run you write the name followed by a pair of brackets, which is called calling it, and you may do that as often as you like.

A call comes back

This is the part that makes procedures worth having rather than merely tidy. When a call is reached, the program goes off and runs the block, and when the block runs out it comes straight back and carries on from the line just after the call — not from the top of the program, and not from the top of the block. So a call behaves like a single line as far as the program around it is concerned, however many lines are hiding inside it. That is what lets you drop a call into the middle of anything at all, including into the body of a loop, without having to think about what the block contains.

Worked example

A program prints 4. Then it calls a procedure whose block prints 8 and then prints 2. Then it prints 6. In what order do the numbers appear?

  1. The first line prints 4, because nothing has been defined that would change what an ordinary line does.

    A program with procedures in it is still read from the top down. Only the calls take a detour.

Try it together

Now count together. A procedure named tick has one printing line in its block. The rest of the program is a loop over range(1, 6) whose only line is a call to tick.

Count the calls before you count anything that gets printed.

    1.How many times is tick called?

    Have a go

    Have a go on your own. A procedure named hop has one printing line in its block, and the program calls hop on three separate lines. How many numbers does the program print?

    Ready to practice?

    Eight questions on what you have just read. Nothing is timed, and you can play as many times as you like.

    Print a worksheet