Skip to main content

Foundations of Python Programming: Functions First

Section 5.3 Logical operators

There are three logical operators: and, or, and not. All three operators take boolean operands and produce boolean values. The semantics (meaning) of these operators is similar to their meaning in English:
  • x and y is True if both x and y are True. Otherwise, and produces False.
  • x or y yields True if either x or y is True. Only if both operands are False does or yield False.
  • not x yields False if x is True, and vice versa.
Look at the following example. See if you can predict the output. Then, Run to see if your predictions were correct:
Although you can use boolean operators with simple boolean literals or variables as in the above example, they are often combined with the comparison operators, as in this example. Again, before you run this, see if you can predict the outcome:
The expression x > 0 and x < 10 is True only if x is greater than 0 and at the same time, x is less than 10. In other words, this expression is True if x is between 0 and 10, not including the endpoints.

Note 5.3.1. Common Mistake!

There is a very common mistake that occurs when programmers try to write boolean expressions. For example, what if we have a variable number and we want to check to see if its value is 5 or 6. In words we might say: “number equal to 5 or 6”. However, if we translate this into Python, number == 5 or 6, it will not yield correct results. The or operator must have a complete equality check on both sides. The correct way to write this is number == 5 or number == 6. Remember that both operands of or must be booleans in order to yield proper results.
Check your understanding

Checkpoint 5.3.2.

    What is the correct Python expression for checking to see if a number stored in a variable x is between 0 and 5.
  • x > 0 and < 5
  • Each comparison must be between exactly two values. In this case the right-hand expression < 5 lacks a value on its left.
  • 0 < x < 5
  • Although most other programming languages do not allow this syntax, in Python, this syntax is allowed. Even though it is possible to use this format, you should not use it all the time. Instead, make multiple comparisons by using and or or.
  • x > 0 or x < 5
  • Although this is legal Python syntax, the expression is incorrect. It will evaluate to true for all numbers that are either greater than 0 or less than 5. Because all numbers are either greater than 0 or less than 5, this expression will always be True.
  • x > 0 and x < 5
  • Yes, with an ``and`` keyword both expressions must be true so the number must be greater than 0 an less than 5 for this expression to be true.
You have attempted of activities on this page.