Logical Operators
A logic error is a mistake where a program runs but the result is wrong. Choosing and when you need or (or the other way round) causes one, because the condition is still valid Python — nothing crashes, but the test gives the wrong answer for some inputs, so the rule you meant is broken.
To correct the condition, put the rule into words first, then ask how many parts must be true. If every part has to be true, join the tests with and. If any single part being true is enough, join them with or.
A pool stays open if the water is warm and a lifeguard is on duty, because both have to hold. A machine stops if the guard is opened or the stop button is pressed, because either one alone must halt it.
Validation catches people out because the same two limits can be written in two ways. A value inside a valid range must be above the lower limit and below the upper limit. A value outside the range is invalid as soon as it is below the lower limit or above the upper limit.
| What you are testing | Condition for limits 2 and 8 | Operator |
|---|---|---|
| Value is inside the range (valid) | players >= 2 and players <= 8 | and |
| Value is outside the range (invalid) | players < 2 or players > 8 | or |
A bowling alley takes bookings for 2 to 8 people. The test players < 2 or players > 8 rejects a party of 1 because the first comparison is true, and a party of 10 because the second is, and one true comparison is enough. Change that or to and and you are asking for a number below 2 and above 8 at the same time, which nothing can be, so the message never appears even though the program runs happily.
players = int(input("How many players? "))
if players < 2 or players > 8:
print("Sorry, bookings are for 2 to 8 people")
else:
print("Lane booked")Output when the user types 10:
How many players? 10
Sorry, bookings are for 2 to 8 peopleWork out the rule in words first, then pick the operator to match it — that is what puts the logic error right.
Edexcel GCSE Computer Science · Logical Operators