Grade 8 Computer Science — Procedures, and calling them
Read a program that gives a block of lines a name, and say what runs, when, and how many times.
Name: ________________________
1.The named block below is called twice. How many numbers does it print?
def show(): print(1) print(2) show() show()2.A loop calls a block that calls another block. How many numbers does it print?
def inner(): print(1) def outer(): inner() inner() for n in range(1, 5): outer()3.A procedure whose body is a single printing line is used in five different programs. Match each way of using it to how many times its body runs.
- Defined but never called
- Called once at the end of the program
- Called inside a loop over range(1, 6)
- Called twice, and again inside a loop over range(1, 5)
- Called inside a loop over range(1, 3) that itself sits inside a loop over range(1, 5)
- 1
- 8
- 6
- 0
- 5
4.One of these four lines never runs at all. Which one?
def alpha(): print(1) def beta(): print(2) alpha() print(3)- a) The line printing 1
- b) The line calling alpha
- c) The line printing 3
- d) The line printing 2
5.A program has a procedure called show. Sort each of these by whether it makes the body of show run.
Groups: Makes the body run · Does not make the body run
- Writing show() on a line of its own
- Writing show() as the last line of the program
- Writing show() inside a procedure that is never called
- Writing def show(): with lines indented underneath it
- Writing show() inside a loop that goes round three times
6.Read this program from the top down. How many numbers does it print?
def show(): print(5)- a) 1
- b) 5
- c) It cannot be run at all
- d) 0
7.Follow this code by hand. How many times does the line printing 3 run?
def step(): print(3) for n in range(1, 5): step()8.One line prints before the call is reached. How many numbers does it print?
def show(): print(7) print(0) show()
Answer key — Grade 8 Computer Science — Procedures, and calling them
- 1. 4
- 2. 8
- 3. Defined but never called → 0; Called once at the end of the program → 1; Called inside a loop over range(1, 6) → 5; Called twice, and again inside a loop over range(1, 5) → 6; Called inside a loop over range(1, 3) that itself sits inside a loop over range(1, 5) → 8
- 4. d) The line printing 2
- 5. Writing show() on a line of its own → Makes the body run; Writing def show(): with lines indented underneath it → Does not make the body run; Writing show() inside a loop that goes round three times → Makes the body run; Writing show() inside a procedure that is never called → Does not make the body run; Writing show() as the last line of the program → Makes the body run
- 6. d) 0
- 7. 4
- 8. 2