Logical ops python

Author
Affiliation

Clayton Cafiero

University of Vermont

Published

2025-09-23

Python’s logical operators and, or, and not

Logical operations are performed in Python with the keywords and, or, and not. They correspond almost exactly to the logical operators \land, \lor, \neg. Here are some examples.

>>> True and False
False
>>> True or False
True
>>> not True
False
>>> True and not False
True

 

How do they differ from the logical operators \land, \lor, \neg? Well, in the world of strict Boolean logic everything is two-valued, and expressions—Boolean formulas—always evaluate to logical true or logical false. That’s not strictly the case in Python. What is always the case in Python is that expressions with and, or, and not will always evaluate to something with a truth value (which is almost everything in Python). That means that sometimes we get suprising results. For example,

>>> True and True  # This works as expected.
True
>>> True and 'peanut butter'   # This one might surprise you.
'peanut butter'

 

What just happened? Python’s and will evaluate subexpressions as needed and the entire expression will evaluate to the last value Python needed to evaluate to determine the truth value of the entire expression—not necessarily True or False. If the left-hand operand is false or falsey (any zero numeric value or any empty sequence or the empty set), Python sees it doesn’t need to evaluate the right-hand side, so it returns the last evaluation (and remember: literals are expressions which evaluate to themselves). So we get results like this:

>>> '' and True
''
>>> [] and True
[]
>>> {} and True
{}
>>> () and True
()

 

In each case, the left-hand side evaluates to something falsey (empty sequence or empty set), so the result is that first falsey value. Python never bothers to evaluate anything on the right-hand side because false and anything is false.

When we try this:

>>> True and 'peanut butter'
'peanut butter'

 

Python sees True on the left-hand side, therefore it must evaluate the right-hand side to see if the entire expression is true (or truthy) and, again, it returns the last thing it evaluated. 'peanut butter' is a non-empty sequence, and thus is truthy.

Now what happens with or? That’s an exercise for you.

© 2025 Clayton Cafiero.

No generative AI was used in writing this material. This was written the old-fashioned way.