/ if statements

If Statements in Python

An important part of coding in Python is learning to express conditional logic. Python has a class designated specifically for this called Boolean.

In this tutorial, we’ll cover the basics of the Boolean class and show you what role it plays in developing important coding tools, such as if, else, and elif statements.

Statements are the smallest, most independent elements of coding. You can think of them as your building blocks. Most programs that you write will be made of many individual statements, which act as instructions that your Python interpreter can execute.

To keep your code flexible and efficient, you will only want to execute certain statements sometimes. That's where Boolean logic plays an important role. Before statements run, we want to check conditions and execute based on those conditions. In this way, we can construct code that makes decisions automatically depending circumstances.

We’ll introduce you to some key concepts to help you understand how the Boolean class operates. You will learn to evaluate data under specific conditions and execute commands accordingly. In our pre-built coding cells, you will be able to practice executing different commands depending on the population size of the individual city your code is assessing. You will learn to think about population size and express some information depending on the different sizes of those populations.

In our final project, you will create your own blocks of code that use conditional statements to execute different actions based on varying population sizes.

But before we jump in, there are some terms you will need to understand. For convenience, we'll add a quick glossary here that you can refer back to if you come across something confusing.

Boolean class: A built-in Python class used for storing True and False values.

Boolean values: The two values of the Boolean class: either True of False.

Boolean logic: a specific way of developing or analyzing problems that breaks them down into questions answerable by True or False.

Boolean expressions: The result of Boolean Logic, Boolean expressions are the specific expressions that evaluate to True or False.

Comparison operators: The specific syntax in Python that initiates comparison, outputting Boolean values.

Using the Boolean class

The Boolean class allows us to build functions that can assess different conditions and execute lines of code depending on the situation. This is what allows code to be agile, adaptive, and most importantly, efficient. The Boolean class has two values: True and False.

Let's practice some basic assignment so we can get more familiar with how Booleans function under the hood.

In order to do this, we'll assign a Boolean value to a variable and then print() the type() of that variable.

Note that even though the Boolean values look like strings, they are an entirely separate class with their own functionality. This functionality allows them to be used as the basic building blocks of conditional logic.

In the shell below we've:

  1. Assigned True to the variable t and False to the variable f
  2. Used the print() function and the type() function to display the type of both t and f

Click run and see what happens!

Rather than outputting to a type you may be familiar with already, such as int or float, we see bool here, which is short for Boolean.

By the end of this tutorial, you’ll understand how to design code so that Python will read your code, make assessments of the Boolean values, and execute based on what values are outputted behind the scenes.


When programming in Python, you can use comparison operators to initiate Boolean expressions. By placing a comparison operator between two values, you are asking for the relationship between those two values in terms of Boolean values. The Python shell will return either True or False.

For example, a basic comparison expression is 2 == 2. The code == is asking if 2 is equal to 2. When the two numbers are compared, either True or False is returned. In the case of 2 == 2, our Python interpreter returns True.

Below, we have a list of specific comparison operators to help you understand the types of comparisons you can make.

  • == returns True if both variables are equal and False if they are not. == can be linguistically read as “is equal to.” For example, the expression “2==4” is evaluating “2 is equal to 4,” which, if course, it is not and so will return False.

  • != returns True if both variables are not equal, and False if they are equal. != can be read linguistically as “is not equal to.” For example, 2!=4 is evaluating “2 is not equal to 4.” This will evaluate as True.

  • > returns True if the first variable is greater than the second variable, and False if it is not.

  • < returns True if the first variable is less than the second variable, and False if it is not.

  • >= returns True if the first variable is greater than or equal to the second value, and False if it is not.

  • <= returns True is the first variable is less than or equal to the second variable, and False if it is not.

If you run these comparisons using the print() statement, you'll see that they return Boolean values.

For example:

    * print(2 == 2)   #returns True
    * print(2 !=  2)   #returns False
    * print (4 >= 2)  #returns True
    * print(4 <= 2)   #returns False

Comparison outputs can be assigned to variables and you can also compare strings, floats, and lists.

In the same way 5 == 5 returns True, so too does “Dataquest” == “Dataquest”

Comparisons can also include portions of lists.

For example, if you have a list:

list = [10, 20, 30]
list[0] < list[1] #returns True
list[0] > list[1] #return False

List comparison will come in handy when we begin learning if statements later in this post. Sometimes, your code will need to fetch not just arithmetic comparisons, but textual ones as well. This functionality allows you to compare data sets that contain integers and floats, but also strings and lists. This diverse functionality is critical for functions like web scraping.

Sometimes, your comparisons will need to use a more specific range. For example, you might want to only return certain data between a range of numbers. For this, we have Python's and and or operators. This will allow you to stack your conditions.

When you use the and operator, both conditions must be true for it to return True.

population = 1000
population > 500 and population < 600 

#returns False because both conditions are not true 

When you use the "or" operator, just one condition needs to be true for the code to evaluate to True.

  population = 1000
  population > 500 or population < 600
  #returns True because only one of the conditions needs to be true

Keep this in mind. In the final project, you'll need to utilize these skills to specify a range for your inquiry.

In this section, we've learned a lot about initiating comparisons. Let's practice to see how some of these concepts work.

In the shell below:

  1. Write a Comparison Operator to assess if 1000 is greater than 500. Place that comparison inside a print() statement

  2. Write a Comparison Operator to assess if 1000 is less than 500. Place that comparison inside a print() statement

  3. Write a Comparison Operator to assess if 1000 is not equal 500. Place that comparison inside a print() statement

  4. Write a Comparison Operator to assess if 1000 is equal to 1000. Place that comparison inside a print() statement

Really great work! In the next section, we'll show you how these comparison operators fit into if statements.

Using If Statements

Now that you’ve got the basics of Boolean under your belt, we can move on to how to use Booleans to express conditional logic using Python’s if operator. if tests the existence of certain conditions and will execute lines of code situationally.

Here is a diagram to help you visualize this process:


Our if statements will only execute if the condition outputs to True. For example, if you have a list of cities, but you only want to print the cities that have populations of above 500, if statements can designate that the print() statement only executes if the variable population is above 500.

When formatting your if statements, make sure that you:

  • End each conditional statement with a colon (:)
  • Indent the code below the conditional statement

This format will tell the Python interpreter that this specific execution is designated to only those conditions, rather than just executing no matter what.

Note that if you are using if, your code must evaluate to True in order to execute. Here is a general representation of this.

If (variable) is (condition):
    Executed code

In order to explore multiple avenues with if statements, you can stack if statements to account for multiple situations. For example:

population = 1000
if population > 500:
        print(“Above 500”)
    if population < 500:
        print(“Below 500”)

This code will print “Above 500.” When the first line of code is evaluated, the expression returns True, and so, the following action is executed. When the second line is evaluated, the expression returns False and therefore is ignored. The True and False returns happen behind the scenes, so don’t expect them to be expressed unless you specifically ask for the type().

Great! We've learned how to use some basic if expressions. Let's practice by seeing if there are plenty of fish in the sea.


In the editor below, we've set the the number of fish to 1500.

  1. Write an if expression that tests to see if the population of fish is greater than 1000

  2. If it is, print the declaration: "There are plenty of fish in the sea."

Looks like there are plenty of fish in the sea!

You've written your first if statement—a crucial building block to understanding how to think like a data ecientist.

Nesting if statements

In Python, you can nest if statements. You can think of nesting as building something within a larger structure, just like a bird's nest.

This is a useful tactic to keep your code tight and concise. To nest code, you simply indent it further. This will indicate to the Python reader that you are placing those executions under the larger umbrella of your conditional logic.

The innermost statement can only execute if the outer most statement is True. In the following example, we’ll write some code that only prints “Huge population” after the code has evaluated if the population is above 500 and 1000.

Run the lines of code below and see what happens when we nest if statements.

This code checks the first condition, which evaluates True, allowing the reader to move on to the nested condition. Once that condition evaluates True, the reader will execute the command within that condition.

The population is greater than 500, and it is also greater than 1000, and so, the reader will execute "Huge population", which seems accurate! Note the inquisitive nature of this operation. The code can check a low value and then try some increment higher, returning an assesment that's more specific. This mindset will be useful when thinking about designing code that tests variable values for range.

Else statements

Above, we went over how to nest using multiple if statements. But if you don’t want to account for every possible situation, you can use Python’s else operator to account for all other situations. If the condition does not meet the specified criteria, the else statement will execute a piece of specified code. In the code below, we’ll print “Big population” if the code is above 1000 and “Small population” if all other conditions fail.

population = 500
if population >  1000:
    print(“Big population”)
    print(“Small population”)

Note that the syntax for the else statement treats it as a complete expression on its own. So after else, close the statement with a colon (:) and indent the executable code.

Here's the same diagram for if statements, with an else statement added, to help you get a feel for the continuity that else statements provide.


Elif statements

Another control statement you can use is elif, which is short for “else if.” This generally renders else optional, because it adds a level of continuity to your work. You can think of it as a shortcut to use when chaining if/else statements.

In the following example, we’ll show you what stacked conditional statements can look like when you use all three: if, elif and else statements.

population = 1000
if population < 500:
	print(“Small Population”)
elif population <= 1000:
	print(“Big Population”)
elif population <= 2000:
	print(“Huge Population”)
	print(“Mega Population”)

This code will print “Big Population” because it has checked the values and found the condition to be True for the elif statement <= 1000. All of the other conditions will be ignored.

Project: checking a city's population

As some final practice, create your own piece of code that uses each conditional statement to check if the population of a city is between 0-100, 101-200, or 201-300. Then, print either that the population is low, medium or high. In this exercise, play with the variable to see how the output changes and note how your code executes different statements as the number changes.

Here are the steps you should follow:

  • Set your variable, population between 0-100
  • Write an if statement that checks if your population is greater than 0 and less than 100 and prints "low" if it is
  • Write an elif statement that checks if your population is greater than 101 and less than 200 and prints "medium" if it is
  • write an elif statement that checks if your population is greater than 201 and less than 300 and prints "high" if it is
  • write an else statement that prints "Too big to count!" for anything over 300

Notice how you had to narrow the range by combining certain conditional opperators using and / or. It will be useful to practice thinking in this way, because many real world problem sets will require you to set limits and write more complicated code to account for more complicated situations.