Skip to content

Python Conditionals, Booleans, and Comparisons

Python Conditionals, Booleans, and Comparisons Cover Image

Python provides a number of intuitive and useful ways in which to check for conditions, comparisons, and membership. In this tutorial, you’ll learn how to use Python to branch your code using conditionals and booleans. You’ll also learn how to check for membership of an item or items, in order to control the flow of your program. All of this serves to allow us to make decisions in our code, which opens up many new opportunities in our programming journey!

Python Booleans

Almost all programming languages contain the concept of a boolean. Booleans are named after a mathematician named George Boole, who defined a system for identifying the truths-ness (or truth value) of any given expression. Put simple, any boolean expression can be expressed as either True or False. Either something is or isn’t true.

Before diving further into the details, let’s speak quick about the semantics of how the value of True is written. For something to be a boolean in Python, it needs to be spelled exactly as True. This means that TRUE and true would not be a boolean value. Similarly, the string 'True' is also not a boolean.

Let’s confirm this quickly by checking the types of some of these options:

# Checking the types of booleans
a = True
b = 'True'

print('The type of a is: ', type(a))
print('The type of b is: ', type(b))

# Returns
# The type of a is:  <class 'bool'>
# The type of b is:  <class 'str'>

Booleans can be used as any other value in Python. For example, you can assign the variables, as we did in the example above. You can also store them in different container types, such as lists.

Where this gets very interesting is that while we can assign a boolean value to a variable, all other Python objects have an inherent truthy-ness to them. What this means is that there is a boolean value assigned to, say, strings such as 'datagy'.

We can check the boolean value of any Python object by using the bool() function. The function will return either a True or False value.

Let’s take a look at a few samples and see if you can pick out some rhyme or reason behind this:

# Checking the truthy-ness of Python Objects
print("'hello' has a boolean value of: ", bool('hello'))
print("'' has a boolean value of: ", bool(''))
print("0 has a boolean value of: ", bool(0))
print("10000 has a boolean value of: ", bool(10000))

# Returns:
# 'hello' has a boolean value of:  True
# '' has a boolean value of:  False
# 0 has a boolean value of:  False
# 10000 has a boolean value of:  True

While it might seem like there isn’t any logic behind what’s True and what’s False in Python, it’s actually quite straightforward! In essence, most objects are True. There are actually very few rules in Python for when an item would evaluate to False. These are:

  • Any representation of zero, whether it’s an integer value such as 0 or a floating point value of 0.0
  • Any value that is either set to False or None
  • Any empty sequence object, such as a string or other object types that you may not know of yet such as lists

Anything that doesn’t fit any of these criteria is actually True!

Python Comparisons Operators

There are many other ways to generate boolean values. One of these is to use comparison operators, which result in a boolean value indicating that a comparison is either True or False. There are six main comparison operators in Python, many of which are probably familiar with from math class!

Let’s take a look at these operators:

x == yx is equal to y3 == 2False
x < yx is less than y3 < 2False
x <= yx is less than or equal to y3 <= 2True
x != yx is not equal to y3 != 2True
x > yx is greater than y3 > 2True
x >= yx is greater than or equal to y3 >= 2True
The different comparison operators in Python

We can use these comparison operators in many different ways. For example, you can use them in functions to check if, say, users are logged in to an application or if a person meets certain criteria.

Let’s see how we can write a function that checks whether a person is legally allowed to get their driver’s license in Canada, where the legal age is 16:

# Writing a function with a comparison operator
def can_drive(age):
    return age >= 16


# Returns: 
# True
# False

In our function, we pass in an argument representing someone’s age and check if the value is greater than or equal to 16.

Some Notes on Comparisons with Data Types

When we use Python comparison operators, it’s important to get a good handle on how they work with different data types. First, let’s take a look at how they work with integers and floats. Conveniently, these work in the way you’d expect:

# Comparing floats and integers
3 == 3.0        # True
3 < 3.0         # False

What may surprise you is that we can actually compare greater than and less than operators. Python interprets strings as their ASCII codes.

Let’s see what this looks like:

# Comparing two strings in Python
'a' == 'A'      # False
'a' > 'A'       # True

While the first statement may not surprise you entirely, the second one may cause you to scratch your head a bit. You can use the ord() function to check the ASCII value of any string. When we convert the values to their ASCII values we can see that this comparison makes a lot of sense:

# Converting strings to ASCII Values

# Returns
# 97
# 65

In the next section, you’ll learn how to use logical operators in Python!

Python Logical Operators: Combining Booleans

Another way that we can check the truthy-ness of Python statements is to use logical operators. These operators are represents by and, or, and not. They evaluate against a boolean expression and have different truth tables associated with them.

Before diving into the truth tables, let’s take a look at an example of how these work:

# Using the and Logical Operator in Python
print(3 > 2 and 1 < 5)

# Returns: True

The way that this works is by ensuring that both of the booleans are equal to True. We can even go further chain them even further:

print(3 > 2 and 1 < 5 and 3 < 2)

# Returns: False

The section below feels a bit academic but it’s an important and logical foundation for your programming adventures:

Truth Table for and

The table below shows the truth relationship between two variables for and:

xyx and y
The truth table for the and logical operator

What the table above shows is that any operation with and where not all values evaluate to True, the expression will evaluate to False.

Truth Table for or

The table below shows the truth relationship between two variables for or:

xyx or y
The truth table for the or logical operator

With an or expression, only one side of the relationship needs to evaluate to True for the whole expression to evaluate to True.

Truth Table for not

The not operator is used to invert a boolean expression. Because of this, it doesn’t logically compare between two values but simply inverts them.

xnot x
The truth table for the not logical operator

Python Conditional Flow: If-Else

We can make even better used of booleans when we used them to control the flow of our program. We can do this using if-else statements. These statements are used to run a certain piece of code if a condition is met.

If you’re coming from other programming languages, or Excel, you may be familiar with the concept of if and else. Python adds a unique third keyword, elif, which stands for else-if. This allows us to embed additional conditions into our flow.

Let’s table a look at a quick example how that can work:

# Using elif to control the flow of your code
def mealtime(hour):
    if hour <= 9:
        print("It's breakfast time!")
    elif hour <= 13:
        print("It's lunch time!")
        print("It's dinner time!")


# Returns:
# It's breakfast time!
# It's lunch time!
# It's dinner time!

The way that this works is that Python will first check if our first condition is True. If not, it moves to the elif and checks if that condition is True. If it is, it executes that code and the flow terminates. If neither condition is True then the else flow runs. What’s more is that we can even include additional elif statements to evaluate multiple conditions.

Multiple Conditions in Python if-else

We can even include multiple conditions in a Python if-else statement. Now that you have a strong understanding of how truth tables work in Python using and, or, and not keywords. This allows us to embed even further flow control in our programs.

Let’s take a look at a fun example! We can build a function that takes two arguments:

  1. Whether or not you overslept and
  2. Whether it’s a workday or not

Our function will tell us whether we need to jump out of bed and start getting ready. Let’s get started on building this function:

# Building a function with logical operators
def hurry_out_of_bed(overslept, workday):
    if overslept and workday:
        print('HURRY! Get out of bed!')
    elif not overslept and not workday:
        print("Keep sleeping!")
        print("You're ok!")

hurry_out_of_bed(overslept=True, workday=True)
hurry_out_of_bed(overslept=False, workday=False)

# Returns: 
# HURRY! Get out of bed!
# Keep sleeping!

We can see here that we’ve been able to embed different logical operators in our if-else flow control statement to develop finely-tuned control of our program!

Python Identity Operators

Another helpful set of operators in Python are the identity operators is and is not. What Python does is interpret whether or not the two objects are allocated in the same space in memory. This means that not only are the values the exact same, but they also point to the same space in memory.

Let’s take a look at an example:

# Using Identity Operators in Python
x = 1
y = 1
print(x is y)

# Returns: True

What may surprise you is that when we look at another Python object that these identity operators work differently than perhaps expected. While we haven’t yet covered lists (but you will soon!), lists are what are called container data types. When we create a list, we can store different values in them. Since the number, order, and types of data are unknown when Python creates a list, each list takes up a different spot in memory.

Let’s take a look at the identity operator with lists:

x = [1, 2, 3]
y = [1, 2, 3]

print(x is y)

# Returns: False

This may surprise you. The two lists look exactly the same but Python actually stores them in different places in memory. This is different than the previous example: 5 will always be 5, but our lists may not always be the same.

You can think of this as two boxes. While the boxes may contain the same items, they are very much different boxes!

Let’s see how we can check where something is being stored in memory, using the id() function:

# Checking where items are stored
x = [1, 2, 3]
y = [1, 2, 3]


# Returns:
# 140194042471296
# 140194043772288

To close off this tutorial, let’s take a look at some exercises to help you solidify your learning!

Exercises: Python Conditionals

Use the Python interpreter to develop a function that identifies whether an employee is eligible for a raise or not. Imagine the following scenario:

  • If an employee makes less than $100,000 in sales, they don’t get a raise
  • If they make between $100,000 and $150,000 in sales they get a $2,500 raise
  • If they make more than $150,000 in sales, they get a $5,000 raise

The function should take a single input, the amount of sales. The function should return the amount of the raise.

Use the space below to practise your coding. You can then toggle the section below to see one possible solution.

This is only one possible solution. Part of the beauty of coding is being able to put your own creative spin on things!

def calculate_raise(sales_amount):
    if sales_amount < 100000:
        return 0
    elif sales_amount < 150000:
        return 2500
        return 5000

Conclusion and Recap

In this post, you learned how to control the flow of your program using different boolean expressions. Let’s take a quick look at a recap of what you’ve learned:

  • Python boolean values are either True or False
  • Comparison operators are used to, well, compare two different values for some form of truth
  • Logical operators allow us to use plain English such as and and or to chain different truth values
  • Truth tables can be used to reference how different logical operators work
  • We can control the flow of our program using if-then statements, combined with else and elif

Additional Resources

To learn more about related topics, check out these additional tutorials:


2 thoughts on “Python Conditionals, Booleans, and Comparisons”

  1. Pingback: NumPy for Data Science in Python • datagy

  2. Pingback: Indexing, Selecting, and Assigning Data in Pandas • datagy

Leave a Reply

Your email address will not be published.