Week 9 · Unit 4: Variables in programming · 3 lessons
3
Predict and fix
Computing 6: Unit 4, pp. 52–67
GoalPredict what a program with variables will say, and find and fix a bug in it.
New words
predict · to say what a program will do before you run itbug · a mistake in a programdebug · to find and fix bugstest · to run a program with chosen inputs to see whether it works
Explanation
Before you run a program, read it and predict what will happen. Write down the value of every variable after each block. This is called tracing. Then run the program, or trace it with a friend, and compare the result with your prediction. If they are different, there is a bug. Look at one block at a time. Common bugs are a missing set block, a wrong variable name, a wrong number and a missing space inside a join block. After you fix a bug, test again with different inputs. A program that works for one input may still fail for another.
Worked examples
Step
animal
legs
The sprite says
after the first reply
frog
0
—
after the first say
frog
0
Me too! I like frog
after the second reply
frog
4
—
after the second say
frog
4
4 legs. Great!
Trace the Animal fan program when the user types frog and then 4. The sprite says Me too! I like frog, and then says 4 legs. Great!
This copy of the program has a bug. The set block for animal is missing, so the variable animal still holds its old value, which is 0 in a new project. The sprite says Me too! I like 0.
Another bug is a missing space. If the join block says [Me too! I like] instead of [Me too! I like ], the sprite says Me too! I likefrog. The fix is to add a space at the end of the text.
Class activity
Bug hunt (no computer): write the Animal fan program on paper, one block per line, but make three mistakes on purpose, for example leave out a set block, spell a variable name two different ways and remove a space from a join. Swap papers with a partner. Trace the program with the inputs frog and 4. Write what the sprite would say. Circle each bug and write the fix. Then swap back and check. If you have a computer or tablet, build the program and test the fixed version.
Practice
1
The user types pancakes and then 3. What does the sprite say each time?
First it says You chose pancakes. Then it says 3 coming up!
2
The sprite says ‘Hello 0’ instead of ‘Hello Mia’. Find the bug.
The set block puts the number 0 into name instead of the answer. It should read set [name v] to (answer).
3
A program says ‘Hello Mia’ when the user types Mia, but ‘Hello 0’ when the user types nothing. Why is testing with different inputs important?
A program may work for the input that you tried first and fail for another. Testing with several inputs, including odd ones, finds more bugs.
4
Write down the three kinds of bug that this lesson mentions.
A missing set block, a wrong variable name or number, and a missing space inside a join block.