Menu

Relational Operators

Testing a Range

Some decisions depend on whether a value sits inside a range, between a lowest and a highest allowed value. A range has two boundaries, but a single relational comparison can only test one of them. To check that a value is inside the range you need two comparisons joined with the logical operator AND, one for the lower limit and one for the upper limit.

Testing both limits

A swimming pool runs a junior session for anyone aged 11 to 15, and both of those ages are allowed. Two tests must pass before a swimmer can join: the swimmer must be at least 11 AND at most 15. In symbols that is age >= 11 AND age <= 15. Testing only age >= 11 would let in a 50-year-old, and testing only age <= 15 would let in a toddler, because each comparison on its own ignores the other end of the range.

Age enteredage >= 11age <= 15In range?
9FalseTrueFalse
11TrueTrueTrue
14TrueTrueTrue
15TrueTrueTrue
17TrueFalseFalse

AND gives True only when both sides are True, so a value counts as inside the range only when it passes both comparisons. The ages 11 and 15 pass because >= and <= include the number they compare against. Swap them for > and < and those two swimmers are turned away, even though 11 and 15 are meant to be allowed.

Point the comparisons inwards

The lower limit is compared with >= and the upper limit with <=, so the two comparisons point inwards at the value being tested. Writing age <= 11 AND age >= 15 asks for an age that is no more than 11 and also no less than 15 at the same moment, and no number can do that. The condition is valid code but always evaluates to False, so nobody ever gets in.

The finished condition is a single expression that evaluates to True or False each time it runs, so you can drop it straight into an if statement to choose what the program does next.

Practise this