Menu

Boolean Operators

Boolean Operators

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

Practise this