Booleans
Explore how Booleans represent truth values in Python 3, including the constants True and False. Understand how expressions evaluate to Booleans in different contexts and discover how Python interprets truthiness in various data types.
We'll cover the following...
Booleans are either true or false. Python has two constants, cleverly named True and False, which can be used to assign boolean values directly. Expressions can also evaluate to a boolean value. In certain places (like if statements), Python expects an expression to evaluate to a boolean value. These places are called boolean contexts. You can use virtually any expression in a boolean context, and Python will try to determine its truth value. Different datatypes have different rules about which values are true or false in a boolean context. (This will make more sense once you see some concrete examples later in this chapter.)
You can use virtually any expression in a boolean context.
For example, take this snippet from humansize.py:
size is an integer, 0 is an integer, and < is a numerical operator. The result of the expression size < 0 is always a boolean. You can test this yourself in the Python interactive shell:
Due to some legacy issues left over from Python 2, booleans can be treated as numbers. True is 1; False is 0.
Ew, ew, ew! Don’t do that. Forget I even mentioned it.