A boolean is a variable that is either True or False. We say the datatype of a variable can be booelan. In numeric context, it’s like a number that can either be 0 or 1. In electronics, it’s either high or low.

You can think of it like a light switch, its either on or off. Its based on the smallest unit in a computer, a bit. A bit is a value that is either 0 (False) or 1 (True). You can view a bit as synonym of boolean for now.

Related Course: Complete Python Programming Course & Exercises

Introduction

A boolean values can have either a False or True value. In Python boolean builtins are capitalized, so True and False.

You do not need to explicitly define the data type to boolean.

You don’t need to say “I want to use a boolean” as you would need in C or Java. Instead Python knows the variable is a boolean based on the value you assign.

Compare the code below on boolean definition:

# Java
boolean fun = true;

# Python
fun = true

Boolean in Python

To define a boolean in Python you simply type:

a = False

That creates a boolean with variable name (a), and has the value False.
If you want to set it to on, you would type:

a = True

The value of a variable can be shown with the print function. If you use the Python shell you can just type the variable name:

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

You can also type:

>>> light = 0
>>> light
0
>>>

You might think that that’s a boolean, but if you request the type you get int (number, integer):

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

Python requires you to call the bool() method to convert a number to a boolean.

If you are a Python beginner, then I highly recommend this book.

Cast boolean

You can cast a value to a boolean using the function bool(). If you cast a variable, the data type is changed. In the example below it goes from data type int to boolean.

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

You can verify this by using the type() method call, which returns the datatype.

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

Boolean strings

Sometimes functions return a boolean value. If you define a string (text) you can call several methods on it, all which return a boolean value.

>>> 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
>>>

If you change the string value s, it will return different boolean values.

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

Download exercises