A boolean holds one of two values, True or False. You use them in every if statement and every loop.

They come out of comparisons, and you can combine them with and, or and not.

Booleans are named after the mathematician George Boole. They hold one of two values, True or False.

Let’s delve deep into the realm of booleans in Python, demystifying their usage and importance.

What are Booleans?

In Python the type is written with a capital: True and False. You do not declare the type, Python works it out from the value.

Compare that with Java, where you have to write the type out:

Here’s a simple comparison of boolean declaration between Java and Python:

# Java
boolean fun = true;

# Python
fun = true

Declaring and Using Booleans in Python

To make a variable a with the value False:

a = False

If you wish to change its value to True, simply reassign it:

a = True

Python offers a built-in print function to display the value of any variable. In the interactive Python shell, you can also just type the variable name to view its value.

>>> a = True
>>> print(a)
True
>>> a
True

A variable holding 0 or 1 looks like a boolean but is an integer:

>>> light = 0
>>> type(light)
<class 'int'>

bool() converts anything to a boolean.

Type Casting to Boolean

So bool(1) is True and bool(0) is False.

>>> x = 1
>>> b = bool(x)
>>> print(b)
True
>>> x = 0
>>> b = bool(x)
>>> print(b)
False

You can validate the type conversion using the type() function:

>>> x = 1
>>> type(x)
<class 'int'>
>>> x = bool(x)
>>> type(x)
<class 'bool'>

Boolean Operations on Strings

Strings have methods that return booleans, and they are handy for checking user input.

>>> s = "Hello World"
>>> s.isalnum()
False
>>> s.isalpha()
False
>>> s.isdigit()
False
>>> s.istitle()
True
>>> s.isupper()
False
>>> s.islower()
False
>>> s.isspace()
False
>>> s.endswith("d")
True
>>> s.startswith("H")
True

Change the string and the answer changes with it.

>>> s = "12345"
>>> s.isdigit()
True
>>> s.endswith("d")
False

Two things worth remembering. bool is a subclass of int, so True is 1. And bool of an empty list or string is False, which catches people out.

Reading helps, writing fixes it. PyChallenge has exercises on this and you can try them right now.