Skip to content

Informatics Practices · Ch 3 — Brief Overview of Python

Logical Operators

3.6.4

Logical Operators

Relational operators give single verdicts — True or False. Real conditions, though, are rarely single: "the marks are above 90 AND attendance is above 75", "the day is Saturday OR Sunday". Logical operators exist to combine or reverse such True/False verdicts. A logical operator evaluates to either True or False, based on the logical operands placed on its sides.

Python supports exactly three logical operators: and, or and not. One rule about them must be fixed in memory at the outset: they are keywords and must be written in lower case only — writing AND, Or or NOT is not valid Python.

The three logical operators

OperatorOperationWhat it does
andLogical ANDIf both operands are True, the condition becomes True
orLogical ORIf any of the two operands is True, the condition becomes True
notLogical NOTReverses the logical state of its operand

Seeing each one work

Logical AND. The condition holds only when both sides hold. In the second example below, num2 is -20, so the right-hand comparison fails and the whole condition collapses to False:

>>> num1 = 10
>>> num2 = -20
>>> num1 == 10 and num2 == -20
True
>>> num1 == 10 and num2 == 10
False

Logical OR. The condition holds when at least one side holds. In the first example, num1 >= 10 is True, and that alone is enough. In the second, both sides fail, so the result is False:

>>> num1 = 10
>>> num2 = 2
>>> num1 >= 10 or num2 >= 10
True
>>> num1 <= 5 or num2 >= 10
False

Logical NOT. It takes a single operand and flips it — True becomes False, False becomes True:

>>> num1 = 10
>>> not (num1 == 20)
True
>>> not (num1 == 10)
False

Since num1 is 10, the comparison num1 == 20 is False; not reverses that to True. Conversely, num1 == 10 is True, and not turns it into False.

Important

Write the logical operators in lower case only: and, or, not. They differ in how demanding they are — and needs both operands True, or is satisfied by either one, and not simply inverts whatever it is given. …

Table 3.6Logical operators in Python
OperatorOperationDescriptionExample (Try in Lab)
andLogical ANDIf both operands are True, then condition becomes True>>> num1 = 10
>>> num2 = -20
>>> num1 == 10 and num2 == -20
True
>>> num1 == 10 and num2 == 10
False
orLogical ORIf any of the two operands are True, then condition becomes True>>> num1 = 10
>>> num2 = 2
>>> num1 >= 10 or num2 >= 10
True
>>> num1 <= 5 or num2 >= 10
False