The truth about Boolean values in Python

Introduction

George Boole was an English mathematician who is credited with having invented a branch of algebra in which an expression is evaluated to one of the truth values, true or false. Unsurprisingly, this became known as Boolean algebra (I’m hoping that Thompsonian snark will be a thing in the not too distant future).

This post looks at how all objects in Python can be tested for a truth value and what that means.

True dat

In Python, you can assign True or False to any variable.

That’s all well and good and is very useful if we want to have a binary type value to assign, rather than trying to use 0’s and 1’s,  ‘yes’ or ‘no’ etc., which could cause confusion with your code where you also use those values for other purposes e.g. it probably doesn’t make sense to have 5 -5 = False.

You can’t handle the truth

Additionally, in Python, any object can be tested to see if it is truthy or falsy. What does that actually mean? Take a look at the following code:

 

A nice and simple example but for beginners to Python, the second if statement might cause confusion. Initially, let’s confirm we understand the first if statement; if the foo variable refers to the value 5, that branch runs i.e. bar() is called, if not, that branch is skipped.

What about the second example. What is if foo: doing? This is where Python tests the truthiness or falseness of the foo variable. In short, that statement means if foo is truthy, run that branch, if it is falsy, skip that branch. So bar() will only be called if foo is truthy.

True or False

The truth will set you free

So what determines if something in Python is truthy or falsy? It depends on the type being evaluated. The table below lists the main types within Python. Remember that these are all objects in Python.  (Some other languages consider data types such as strings and tuples to be primitives.)

Type When is it truthy? When is it falsy?
str Not empty Empty, ”
list Not empty Empty, []
tuple Not empty Empty, ()
set Not empty Empty, set()
dict Not empty Empty, {}
int Not zero, 0 Zero, 0
float Not 0.0 0.0
bool True False
NoneType Never Always
Function Always Never
Class Always Never

Let’s go back to that second if statement.

There is a really handy built-in function we can use to tell us if something is truthy or falsy, the bool() function.

Summary

This post began discussing the True and False Boolean values you can assign in Python and then went on to discuss how all objects in Python can be tested for a truth value and what that means. I hope this has been useful.

Till the next time.

Please let me know your thoughts!

This site uses Akismet to reduce spam. Learn how your comment data is processed.