Menu

Programming Fundamentals

Boolean Operators

Contents

  1. Boolean Operators
  2. The not Operator
  3. Range Checks with Boolean Operators
  4. Evaluating Compound Conditions

Boolean operators combine or reverse conditions. The three you need are AND, OR and NOT. In Python they are written in lower case as and, or and not; capitals such as AND are not recognised as operators and cause an error.

A condition that uses Boolean operators is a Boolean expression, so it evaluates to True or False. This is the same type of value produced by a comparison such as points >= 50.

OperatorPythonMeaning
ANDandGives True only when both conditions are true
ORorGives True if either condition is true, or if both of them are
NOTnotReverses a condition: True becomes False and False becomes True

Use Boolean operators when a decision depends on more than one test, or on the opposite of a test. For example, a game might let a player continue only if they have lives left and have not quit. The combined result is still an ordinary Boolean value, so it can be used in an if statement or stored in a variable. The result is always True or False, never a number.

day = input("Day: ")
homework = input("Homework finished? yes/no: ")
if (day == "Saturday" or day == "Sunday") and not (homework == "yes"):
    print("Finish homework first")
else:
    print("Free time")

Output when the user types Saturday, no:

Day: Saturday
Homework finished? yes/no: no
Finish homework first

not is the Boolean operator that reverses a Boolean value: whatever is True becomes False, and whatever is False becomes True. In Python it is always written in lower case.

Reversing a value

Since the result is still a Boolean value, it can be used anywhere a condition is expected, such as the test of an if statement or the value stored in a variable.

Valuenot Value
TrueFalse
FalseTrue

Applying not to a comparison

To reverse a whole comparison, write not in front of it. Putting the comparison in brackets, as in not (temperature > 20), makes it clear that not works on the finished result of the comparison rather than on the variable inside it.

Reversing an equality test gives exactly the same answer as using the not-equal operator. not (basket_items == 0) is logically equivalent to basket_items != 0: both give True when the basket contains at least one item, and both give False when the basket is empty.

Applying not to a Boolean variable

If a variable already holds a Boolean value, not goes straight in front of it, with no comparison needed. if not ticket_paid: runs its block when ticket_paid is False, which is a neat way of testing that a task has not been completed or that something has not happened yet.

ticket_paid = False
print(not ticket_paid)

if not ticket_paid:
    print("Please pay before you travel")

Output:

True
Please pay before you travel

not never changes the value being tested; it only reverses the Boolean result.

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.

A compound condition joins two or more comparisons with and or or, and not reverses a Boolean value. To evaluate one, you play the part of the computer: substitute the values the variables hold, work out each comparison as True or False, then combine those Boolean results using the rules for and, or and not.

The operators are not simply worked through left to right. Precedence decides the order: not is applied first, then and, then or. Two operators with the same precedence are worked left to right. Brackets override all of this, so anything inside brackets is worked out first, then not, then and, then or.

Working through an expression

Imagine a game holds lives = 2, coins = 40 and power_up = False, and the program tests lives > 0 or coins >= 50 and power_up.

StepExpressionWhat happened
12 > 0 or 40 >= 50 and Falsesubstitute the values
2True or False and Falseeach comparison becomes a Boolean value
3True or Falseand is done first
4Trueor is done last

The answer is True. Working left to right would have given (True or False) and False, which is False, so the order really does change the answer.

Because not comes first, not power_up and coins > 20 becomes not False and True, then True and True, which is True.

Brackets decide the grouping

Putting brackets around the or part forces a different order: (lives > 0 or coins >= 50) and power_up becomes (True or False) and False, then True and False, giving False.

Whenever and and or are mixed, add brackets so the grouping you intend is the grouping the computer uses, and so anyone reading the code sees it too. A common mistake is leaving brackets out and assuming the expression is read left to right, which silently changes the logic. Work one operator at a time, writing down the Boolean value of each part, so you can check the final answer.

Also useful