Writing and Refining Algorithms
A logic error is a mistake in the thinking behind a program: the code is valid Python, so it runs, but it produces the wrong result or says the wrong thing.
One frequent logic error is an off-by-one error in range(). range(1, 5) starts at 1 and stops before 5, so it gives 1, 2, 3, 4: four values, not five. To repeat five times you need range(1, 6). The same kind of mistake happens with comparison operators: if 45 points should meet the target, points > 45 leaves 45 out, while points >= 45 includes it.
Conditions can also be in the wrong order. In an if/elif chain, the first true condition wins. If a broad check such as points >= 0 comes before points >= 45, the broad check catches every value and the later target check is never reached. Check the narrow or most important case first.
Other logic errors are easy to spot only by tracing values. You might use the wrong operator, such as area = length + width when you meant length * width, or the wrong variable, such as multiplying price by price instead of by quantity. A counter, running total or flag may never be updated inside a loop, or the line that updates it may sit outside the loop because of wrong indentation. If a while loop’s counter or flag is never changed, the loop can run endlessly. A program may also overwrite a value supplied in the question instead of using it, for example replacing a given budget with a new number before testing it.
total = 0
for lap in range(1, 5):
print("Lap:", lap)
print("Total laps:", total)Output:
Lap: 1
Lap: 2
Lap: 3
Lap: 4
Total laps: 0
Here, range(1, 5) gives four laps if five were intended, and total is never updated, so it stays 0.
Output can be wrong in two ways: the message may not match the required wording, or it may be printed on the wrong path. A line placed after an if/else runs whichever path was taken, so “Please charge now” can appear even when the battery level is fine.
battery = 80
if battery >= 20:
print("Battery OK")
else:
print("Low battery")
print("Please charge now")Output:
Battery OK
Please charge now OCR GCSE Computer Science · Writing and Refining Algorithms
OCR GCSE Computer Science · Selection
OCR GCSE Computer Science · Testing