Python Boolean: A Data Type For Your Logical Conditions — Codefather

One of the data types available in Python is the boolean. Knowing booleans helps create logical conditions in your Python applications.

The boolean is one of the data types provided by the Python programming language. A boolean can have two values: True or False. Booleans allow to create logical conditions that define the behaviour of an application. Boolean operators are used to create more complex logical conditions.

Let’s see how to use booleans in your Python programs!

What is a Boolean in Python?

A boolean is a Python data type that can be either True or False.

Firstly, let’s understand how booleans behave by using the Python shell:

>>> True
True
>>> False
False

As you can see, an expression that just contains the boolean value True is True. In the same way, an expression that only contains the boolean value False is False.

Let’s find out the type returned by the Python interpreter for True and False using the type() function:

>>> type(True)
<class 'bool'>
>>> type(False)
<class 'bool'>

Both True and False are of type bool.

Is the Number 1 True in Python?

This is an interesting question…

How are numbers related to the boolean data type?

Let’s see if we can get the answer from the Python shell when we apply the bool() function to the numbers 0 and 1.

>>> bool(1)
True
>>> bool(0)
False

You can see that the number one is translated to a boolean True and the number zero to a boolean False.

Here is another example with floating point and complex numbers:

>>> bool(10)
True
>>> bool(5.45)
True
>>> bool(3+4j)
True
>>> bool(0.0)
False

This shows that all numbers translate to True unless they are equal to zero.

How Do You Write a Boolean in Python?

We have seen that the values of a boolean are True and False.

Make sure the first letter of True or False is capital otherwise the Python interpreter will not see those as booleans.

See what happens if we use True and False using a lowercase first letter:

>>> true
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'true' is not defined
>>> false
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'false' is not defined

We get back the error “name is not defined”.

How to Use Boolean Variables

We can also assign boolean values to a variable.

For example…

>>> var = True
>>> type(var)
<class 'bool'>
>>> var = False
>>> type(var)
<class 'bool'>

Now, we will write some code that uses boolean variables.

Imagine you are creating a simple program that automates the booking of your meetings. The program looks at the value of the boolean variable calendar_free to understand if a specific time slot is free in your calendar.

We then use an if else statement to book the meeting if the value of calendar_free is True. Otherwise the system is unable to book the meeting.

calendar_free = True if calendar_free is True:
print("Your calendar is free. Booking your meeting.")
else:
print("Your calendar is not free. Unable to book meeting.")

Notice that we are using the is operator to evaluate if the calendar_free variable is True.

Run the program, you will see the following message:

Your calendar is free. Booking your meeting.

Here is what happens when the Python interpreter gets to the if condition:

>>> calendar_free = True
>>> calendar_free is True
True

The expression “calendar_free is True” returns True. That’s why the print statement in the if branch of the if else statement is executed.

How to Evaluate a Boolean Expression in Python

In the previous section we have seen an example of Python boolean expression.

Let’s see another one, slightly different from the first one:

x = 0 while x < 5:
print("The value of x is {}".format(x))
x += 1

We have set the value of the variable x and then we use a while loop to print the value of x as long as x is smaller then 5.

It’s also important to see that at every iteration of the while loop we increase x by 1 (without doing that we would be stuck in an infinite loop).

Here is how the condition x < 5 is evaluated for different values of x:

>>> x = 0
>>> x < 5
True
>>> x = 1
>>> x < 5
True
>>> x = 5
>>> x < 5
False

The execution of the while loop stops when the value of the expression x < 5 is False.

The output of the program is:

The value of x is 0
The value of x is 1
The value of x is 2
The value of x is 3
The value of x is 4

Another Example of Boolean Expression

Imagine you are writing a Python program and you want to define a boolean variable whose value determines if the program is in debug mode or not.

Also, based on that you want to print additional messages that help you troubleshoot potential issues with the program.

Let’s continue working on the program written in the previous section:

x = 0
debug=True
while x < 5:
print("The value of x is {}".format(x))
if debug is True:
print("There are {} iterations left".format(5-x))
x += 1

This time we have set the value of the boolean variable debug to True outside the while loop.

Then we use an if statement to print a debug message if the debug variable is True (once again using the is operator).

The value of x is 0
There are 5 iterations left
The value of x is 1
There are 4 iterations left
The value of x is 2
There are 3 iterations left
The value of x is 3
There are 2 iterations left
The value of x is 4
There are 1 iterations left

I don’t find the output of our program very clear…

What can we do to make the messages easier to read?

x = 0
debug=True
while x < 5:
print("INFO: The value of x is {}".format(x))

if debug is True:
print("DEBUG: There are {} iterations left".format(5-x))
x += 1

I have applied a very simple change by adding INFO and DEBUG before the two types of messages. This immediately clarifies for the user if a message is an informational or a debug message.

INFO: The value of x is 0
DEBUG: There are 5 iterations left
INFO: The value of x is 1
DEBUG: There are 4 iterations left
INFO: The value of x is 2
DEBUG: There are 3 iterations left
INFO: The value of x is 3
DEBUG: There are 2 iterations left
INFO: The value of x is 4
DEBUG: There are 1 iterations left

A lot better!

Can You Use == For Boolean?

In the previous examples we have used the is operator as part of boolean expressions.

Can we also use the == operator in boolean expressions?

>>> var = True
>>> var is True
True
>>> var == True
True
>>> var is False
False
>>> var == False
False

After assigning the value True to a variable, we get exactly the same output either with the is operator or the == operator.

So, we can use the == operator with a boolean too.

Also, here is a way to simplify the expression “var is True”:

>>> var is True
True
>>> var
True

You can see that we get back True as result even if we omit the “is True” part of the expression.

So, the calendar booking program we have seen before can be simplified:

calendar_free = True if calendar_free:
print("Your calendar is free. Booking your meeting.")
else:
print("Your calendar is not free. Unable to book meeting.")

Run the program on your machine and make sure it works as expected.

What Are the 3 Boolean Operators?

There are three boolean operators that can be very handy when using boolean expressions in your Python applications.

Not Operator

The not operator inverts the value of the boolean passed to it.

>>> not True
False
>>> not False
True

We can use the not operator to rewrite the logic of the calendar booking program:

calendar_free = True if not calendar_free:
print("Your calendar is not free. Unable to book meeting.")
else:
print("Your calendar is free. Booking your meeting.")

The output will be the same as before (notice that we have swapped the two print statements considering that the logic of the if-else statement has changed after adding the not operator):

And Operator

The and operator applies to two expressions and follows the logic below:

The result of the and operator is True only if both expressions the operator is applied to are True.

We can apply the and operator to the calendar booking application.

After adding a new boolean condition meetings can only be scheduled if your calendar is free and if the day of the meeting is a weekday (it’s not in the weekend):

calendar_free = True
weekday = False
if calendar_free and weekday:
print("Your calendar is free. Booking your meeting.")
else:
print("Your calendar is not free. Unable to book meeting.")

This time the program won’t be able to book a meeting because weekday is False and hence the result of the and expression is False.

$ python book_meeting.py 
Your calendar is not free. Unable to book meeting.

Or Operator

The or operator applies to two expressions and follows the logic below:

The result of the or operator is True if at least one of the expressions the operator is applied to is True.

Conclusion

In this tutorial, we have seen what a boolean is, how it relates to other Python data types, and how to work with boolean expressions.

I hope the examples we went through have helped you understand how to use boolean values in your Python programs.

Let me know in the comments if you have any questions :)

Originally published at https://codefather.tech on February 28, 2021.

I’m a Tech Lead, Software Engineer and Programming Coach. I want to help you in your journey to become a Super Developer!

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store