Menu

Writing and Refining Algorithms

Combining Conditions with and/or

A condition can test two comparisons at once by joining them with and or or. The joined condition is True or False as a whole, and the if uses that single result to choose a path.

and is true only when both comparisons are true, so one false side makes the whole condition false. or is true when at least one side is true, and is false only when both sides are false. That makes and the stricter choice: use it when every requirement must be met, and or when any one of them is enough.

First comparisonSecond comparisonJoined with andJoined with or
TrueTrueTrueTrue
TrueFalseFalseTrue
FalseTrueFalseTrue
FalseFalseFalseFalse

Each side in full

Each side of and/or must be a complete comparison that repeats the variable, so the computer knows what to test twice. For a weekend check you might write day == "Saturday" or day == "Sunday": each half would make sense on its own. Writing day == "Saturday" or "Sunday" leaves out the variable after or. It runs, but the second half is not a comparison, so the day is never checked against "Sunday" and the condition can give the wrong result. Using a different variable by accident changes the meaning just as badly.

Worked example

A weather station issues an extreme warning if the temperature is below 0 or above 35, and a cold warning if it is between 0 and 10 inclusive. The first check needs or, because either extreme qualifies; the second needs and, because a cold warning needs the temperature to be inside both limits.

temperature = int(input("Temperature: "))
if temperature < 0 or temperature > 35:
    print("Extreme weather warning")
elif temperature >= 0 and temperature <= 10:
    print("Cold weather warning")
else:
    print("Normal weather")

Output when the user types 40:

Temperature: 40
Extreme weather warning

Typing 40 makes temperature < 0 false but temperature > 35 true, so the or condition is true and the extreme warning prints. For 5 both sides of the first condition are false, so it moves on: 5 >= 0 and 5 <= 10 are both true, giving the cold warning.

Practise this

OCR GCSE Computer Science · Writing and Refining Algorithms