Login
📚 Introduction to Python Programming
Chapters ▾
⇩ Download ▾

4.3 Boolean operations

Learning objectives

By the end of this section you should be able to

  • Explain the purpose of logical operators.
  • Describe the truth tables for and, or, and not.
  • Create expressions with logical operators.
  • Interpret if-else statements with conditions using logical operators.

Logical operator: and

Decisions are often based on multiple conditions. Ex: A program printing if a business is open may check that hour >= 9 and hour < 17. A logical operator takes condition operand(s) and produces True or False.

Python has three logical operators: and, or, and not. The and operator takes two condition operands and returns True if both conditions are true.

Table 4.1 Truth table: p and q.
pqp and q
TrueTrueTrue
TrueFalseFalse
FalseTrueFalse
FalseFalseFalse

Logical operator: or

Sometimes a decision only requires one condition to be true. Ex: If a student is in the band or choir, they will perform in the spring concert. The or operator takes two condition operands and returns True if either condition is true.

Table 4.2 Truth table: p or q.
pqp or q
TrueTrueTrue
TrueFalseTrue
FalseTrueTrue
FalseFalseFalse

Logical operator: not

If the computer is not on, press the power button. The not operator takes one condition operand and returns True when the operand is false and returns False when the operand is true.

not is a useful operator that can make a condition more readable and can be used to toggle a Boolean's value. Ex: is_on = not is_on.

Table 4.3 Truth table: not p.
pnot p
TrueFalse
FalseTrue