Level 1
0 / 100 XP

Booleans

Booleans are commonly used as a True or False statement. The simplest example would be comparing two numbers, is 1 greater than 2?

print( 1 > 2 )

Python will happily tell you that this is a false statement. In Python (and in computer programming in general), you will need to use boolean statements frequently in various scenarios that we will explore here. Let’s take a look at several examples:

Are these numbers equal?

Python
print( 1 == 2 ) print( 2 < 1 )

These will all return False. Note that False is one of the few capitalized keywords in Python. A few examples that will return True are:

Python
print( 2 == 2 ) print( 5 > 1 ) print( 1 < 3 )

We can use booleans to drive our logic in our code like so:

Python
myVar = True if myVar: print("It is true!") else: print("Its false!")

Try changing the value of myVar to False and run the code. Note that we will dive deeper into if..else statements in future lessons.

A very handy use of booleans is to see if a variable is set. You will use this quite frequently when you are querying APIs - sometimes you will attempt to do something like create a user account and you will need to see if the API returned an error. This would be a perfect True or False scenario. Let’s take a look at how we can get a True or False result based on if a variable has a value or not:

Python
myVar = "I am a string and I will return True!" anotherVar = "" print( bool(myVar) ) print( bool(anotherVar) )

Here we are assigning to string variables. The first has text inside the string and the second is empty. If we cast these variables to a boolean, the first returns True and the second returns False. Let’s say for example we have a variable named “apiError”, and we want to display an error message if something goes wrong in our code. We can do that like this:…