Booleans in Python

As far as data types go, the Boolean type is by far the simpler one.

A boolean typed variable is either Trueor False.

Notice the capitalization, that is how you should write these values in Python, not "true" or "false".

Declaring a Boolean Variable

When you assign True or False, the variable is inferred as boolean automatically by the Python intepreter, but you can set that explicitly using the boolkeyword.

my_boolean = True
print(type(my_boolean))
#<class 'bool'>

my_bool = bool(True)
print(type(my_bool))
#<class 'bool'>

Boolean Algebra

To deal with booleans right, it’s important to understand Boolean Algebra.

Boolean algebra has three basic operations: and, or, not.

In Python, these operators are written in lowercase as shown.

The combinations of values for each of these operations are better shown in a Truth table, that allows you to list all possible inputs and outputs.

and Truth Table

Only when both x and y are true, the and operator evaluates to True.

xyx and y
TrueTrueTrue
TrueFalseFalse
FalseTrueFalse
FalseFalseFalse

Example in Python:

x = True
y = False
print(x and y)
#False

or Truth Table

Only when both x and y are false, the or operator evaluates to False.

xyx or y
TrueTrueTrue
TrueFalseTrue
FalseTrueTrue
FalseFalseFalse

Example in Python:

x = True
y = False
print(x or y)
#True

not Truth Table

The not operator simply inverts the input.

xnot x
TrueFalse
FalseTrue

Example in Python:

x = True
print(not x)
#False

Evaluating Boolean Expressions

Comparison expressions that return a boolean value are easily understood if read in plain english.

If I ask: "Is 2 greater than 1?". The answer will be "Yes" or as we now know it True.

This example in Python translates to:

x = 2 > 1
print(x)
#True

The opposite case, 2 is less than 1:

x = 2 < 1
print(x)
#False

Another example would be to check if 2 and 1 are the same, which is False, of course.

x = 2 == 1
print(x)
#False

That’s it for Booleans in Python, if you want to know more on data types in general in Python, read my post on Python Data Types.