Skip to content
Exit presentation

Computational Thinking III: Functions & Debugging

A name for a group of steps

Two bus stops need the same three lines.

Two stops. Three lines print at each one.
Step 1 of 4
  1. Two stops. Three lines print at each one.
  2. The three lines repeat. Box them together.
  3. Named stopRoutine, then called at each stop.
  4. The same eight lines still print.

Switch on the function below. Then read what prints.

Loading lab…

The rule

A function is a named group of lines. Its definition is the lines and their name.

`` function stopRoutine() { print("Bell: two taps"); print("Doors open"); print("Doors close"); } ``

A call is stopRoutine();. It runs the body, the lines inside the curly brackets.

A function gives a group of lines one name. Writing the definition runs nothing. It runs at each call, and what gets printed does not change.

In this editor, a definition may sit below its call.

Before and after naming
Lines writtenLines printed
Repeated88
Named98

The definition takes 5 lines. Two calls take 2 more. That is 7 lines, against 6 copied lines. So at two stops, naming costs 1 more line. The name saves writing when a group repeats many times. Each extra stop adds 1 call line, not 3 copied lines.

Jump to lesson

This track

  1. 0 Start here
  2. 1 A name for a group of steps
  3. 2 What you hand it, and what each end is called
  4. 3 The value it hands back
  5. 4 One call inside another
  6. 5 A print in the middle
  7. 6 One line at a time
  8. 7 Predict, then run
  9. 8 Halve the hunt
  10. 9 The big picture
  11. 10 Track quiz

Other tracks