Finding the bug in code – practice for Years 8–9
Sample questions on Finding the bug in code with the right answer and a worked solution, from easy to hard. In the Pickles Academy app a child gets new questions of the same kind every time, so they can't just learn the answers by heart.
- Subject
- Computing
- Year
- Years 8–9
- Curriculum area
- Algorithms and programming
Question types: Which line has the bug?
Rule: Finding the bug in code
Trace the program with small numbers. Where the values first differ from what they should be, there is the bug.
Common bugs: a product starting at 0 instead of 1, range ending one too early, adding instead of multiplying.
Example: The product of 1 to 4 came out as 6 = 1 × 2 × 3: range(1, 4) should be range(1, 5).
Watch out: Don’t start a product at 0: if p = 0 at the start, multiplying keeps giving 0.
Sample questions
-
Question 1 Easy
The program should print the sum of the numbers from 1 to 6, but it prints 0. Which line has the bug?
1n = 6 2s = 0 3for i in range(1, n + 1): 4 s = s * i 5print(s)
Show the solution
Answer: D) line 4How it works: Line 4 is wrong; it should be: s = s + i. Then the program prints 21.
-
Question 2 Normal
The program should print the sum of the numbers from 1 to 6, but it prints 15. Which line has the bug?
1n = 6 2s = 0 3for i in range(1, n): 4 s = s + i 5print(s)
Show the solution
Answer: C) line 3How it works: Line 3 is wrong; it should be: for i in range(1, n + 1):. Then the program prints 21.
-
Question 3 Hard
The program should print the sum of the even numbers from 2 to 10, but it prints 25. Which line has the bug?
1n = 10 2s = 0 3for i in range(1, n + 1, 2): 4 s = s + i 5print(s)
Show the solution
Answer: C) line 3How it works: Line 3 is wrong; it should be: for i in range(2, n + 1, 2):. Then the program prints 30.
Keep practising in the app
In a minute, your child has their own avatar and a first task. Free, no ads, data in the EU.
Start for free