Menu

Boolean Operators

Range Checks with Boolean Operators

A range check uses a condition to test whether a value lies inside or outside a set of limits. The Boolean operator you choose must match what you are testing: and for inside the range, or for outside it.

Inside the range: use and

To accept a value from 30 to 80 inclusive, both limits must be satisfied. Join the lower-bound comparison and the upper-bound comparison with and:

if tank_level >= 30 and tank_level <= 80:

This condition is true only when the level is at least 30 and at most 80. If either comparison is false, the whole condition is false.

Outside the range: use or

To spot a value below 30 or above 80, either failure is enough. Join a below-the-lower-bound comparison and an above-the-upper-bound comparison with or:

if tank_level < 30 or tank_level > 80:

This is true when at least one side is true. A particular value cannot be both below 30 and above 80, so only one side can be true for any one number.

tank_level = int(input("Enter tank level: "))
if tank_level >= 30 and tank_level <= 80:
    print("Level is safe")
elif tank_level < 30 or tank_level > 80:
    print("Adjust the level")

Output when the user types 25:

Enter tank level: 25
Adjust the level

Match the operator to the test

Swapping the operators changes the meaning. tank_level < 30 and tank_level > 80 asks for a value that is both below 30 and above 80, which is impossible. tank_level >= 30 or tank_level <= 80 is true for every possible value, so it never checks the 30 to 80 range at all. Decide whether you are testing inside or outside, then choose and or or to match.

Practise this