Skip to content
Home » The Boolean Type in Python

The Boolean Type in Python

Spread the love

Today we’ll be talking about the boolean type in Python.

The boolean data type can have only one of two values: True or False.

boolean type

We can assign a boolean value explicitly:

>>> she_is_coming = True
>>> if she_is_coming == True:
...     print("Beware...")
... 
Beware...

>>> winning = False
>>> if winning == False:
...     print("Try harder!")
... 
Try harder!

We can rewrite this code in a more concise manner. In the condition check we can write just she_is_coming, which is equivalent to she_is_coming == True:

>>> if she_is_coming:
...     print("Beware...")

Accordingly, the equivalent of winning == False is not winning:

>>> if not winning:
...     print("Try harder!")

Expressions can evaluate to a boolean value. They can be practically of any length and complexity:

>>> 2 + 3 == 8
False

>>> 3 > -11
True

>>> len("Hi there") < 100
True

>>> ["I", "you", "she", "they"][1] == "they"
False

>>> max([5, 16, 2]) <= len("just counting") + min((7, 0, -3, 8))
False

We can check whether an expression is of boolean type using the type function:

>>> type(2 + 2 == 4)
<class 'bool'>

The boolean values True and False may even be used as numbers. Then True equals 1 and False equals 0:

>>> 2 * True
2

>>> False + 8 - True
7

In such a case the boolean value doesn’t change the numeric type of the expression:

>>> a = False + 3
>>> type(a)
<class 'int'>

>>> b = 3.75 * True
>>> type(b)
<class 'float'>

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

Numbers may also be understood as boolean values. Zero is understood as False, any other number as True.

So, here we have a condition which is not met:

>>> if 0:             # means as much as ‘if False’
...     print(3)
... 

The following two conditions are met:

>>> if 54:            # means as much as ‘if True’
...     print(5)
... 
5

>>> if -56:           # means as much as ‘if True’
...     print("hi")
... 
hi

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Actually, there are a few objects which are evaluated as False:

– the boolean literal False

– numerical 0 values (integer 0, float 0.0, complex 0.0+0.0j)

– empty strings, lists, tuples and dictionaries

– the value None

Other objects are evaluated as True.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.

Here’s the video version of the article:


Spread the love

Leave a Reply