March 3, 2022

Tutorial: Using If Statements in Python

Our life is full of conditions even if we don’t notice them most of the time. Let’s look at a few examples:

  • If tomorrow it doesn't rain, I’ll go out with my friends in the park. Otherwise, I’ll stay home with a cup of hot tea and watch TV.
  • If tomorrow it isn't too hot, I’ll go to the sea, but if it is, I’ll have a walk in the forest. However, if it rains, I’ll stay home.

You get the idea. Let’s see how conditions work in computers. You may already know that programs in Python are executed line by line. However, sometimes, we need to skip some code and execute only some of it only if certain conditions are met. This is where control structures become useful. Conditional statements in Python are built on these control structures. They will guide the computer in the execution of a program.

In this tutorial, you'll learn how to use conditional statements. This guide is for beginners in Python, but you'll need to know some basics of coding in Python. If you don’t, then check this free Python Fundamentals course.

Basic if Statement

In Python, if statements are a starting point to implement a condition. Let’s look at the simplest example:

if <condition>:
    <expression>

When <condition> is evaluated by Python, it’ll become either True or False (Booleans). Thus, if the condition is True (i.e, it is met), the <expression> will be executed, but if <condition> is False (i.e., it is not met), the <expression> won’t be executed.

We are pretty free to decide what conditions and expressions can be because Python is very flexible.

Let’s look at a concrete example.

# Basic if statement
x = 3
y = 10

if x < y:
    print("x is smaller than y.")
x is smaller than y.

First of all, we define two variables, x and y. Then we say that if variable x is smaller than variable y, print out x is smaller than y). Indeed, if we execute this code, we’ll print out this output because 3 is smaller than 10.

Output: x is smaller than y.

Let’s look at a more complex example.

# A slightly more complex example
x = 3
y = 10
z = None

if x < y:
    z = 13
print(f"Variable z is now {z}.")
Variable z is now 13.

In this case, if the condition is met, then a value of 13 will be assigned to the variable z. Then Variable z is now 13. will be printed out (note that the print statement can be used both outside and inside the if statement).

As you can see, we aren't restrained in the choice of an expression to execute. You can now practice more by writing more complex code.

Let’s know see what happens if we execute the following code:

# What happens here?
x = 3
y = 10

if x > y:
    print("x is greater than y.")

Here we changed the direction of the comparison symbol (it was less than, and now it’s greater than). Can you guess the output?

There will be no output! This happened because the condition hadn't been met. 3 is not greater than 10, so the condition evaluated to False, and the expression wasn’t executed. How do we solve this problem? With the else statement.

else Statement

What if we want to execute some code if the condition isn't met? We add an else statement below the if statement. Let’s look at an example.

# else statement
x = 3
y = 10

if x > y:
    print("x is greater than y.")
else:
    print("x is smaller than y.")
x is smaller than y.

Output: x is smaller than y.

Here, Python first executes the if condition and checks if it’s True. Since 3 is not greater than 10, the condition isn't met, so we don’t print out “x is greater than y.” Then we say that in all other cases we should execute the code under the else statement: x is smaller than y.

Let’s get back to our first example of a conditional statement:

If tomorrow it doesn't rain, I’ll go out with my friends in the park. Otherwise, I’ll stay home with a cup of hot tea and watch TV.

Here the else statement is “Otherwise.”

What happens if the condition is met?

# What if the condition is met?
x = 3
y = 10

if x < y:
    print("x is smaller than y.")
else:
    print("x is greater than y.")
x is smaller than y.

In this case, Python just prints out the first sentence as before.

Output: x is smaller than y.

What if x is equal to y?

# x is equal to y
x = 3
y = 3

if x < y:
    print("x is smaller than y.")
else:
    print("x is greater than y.")
x is greater than y.

The output is clearly wrong because 3 is equal to 3! We have another condition outside the greater or less than comparison symbols; thus, we have to use the elif statement.

elif Statement

Let’s rewrite the above example and add an elif statement.

# x is equal to y with elif statement
x = 3
y = 3

if x < y:
    print("x is smaller than y.")
elif x == y:
    print("x is equal to y.")
else:
    print("x is greater than y.")
x is equal to y.

Output: x is equal to y.

Python first checks if the condition x < y is met. It isn't, so it goes on to the second condition, which in Python, we write as elif, which is short for else if. If the first condition isn't met, check the second condition, and if it’s met, execute the expression. Else, do something else. The output is “x is equal to y.”

Let’s now get back to one of our first examples of conditional statements:

If tomorrow it isn't too hot, I’ll go to the sea, but if it is, I’ll have a walk in the forest. However, if it rains, I’ll stay home.

Here, our first condition is that tomorrow it’s not too hot (if statement). If this condition isn't met, then we go for a walk in the forest (elif statement). Finally, if neither condition is met, we’ll stay home (else statement).

Now let’s translate this sentence into Python.

In this example, we're going to use strings instead of integers to demonstrate the flexibility of the if condition in Python.

# elif condition
tomorrow = "warm"

if tomorrow == "warm":
    print("I'll go to the sea.")
elif tomorrow == "very hot":
    print("I'll go to the forest.")
else:
    print("I'll stay home.")
I'll go to the sea.

Python first checks if the variable tomorrow is equal to “warm” and if it is, then it prints out I'll go to the sea. and stops the execution. What happens if the first condition isn't met?

# Tomorrow is very hot
tomorrow = "very hot"

if tomorrow == "warm":
    print("I'll go to the sea.")
elif tomorrow == "very hot":
    print("I'll go to the forest.")
else:
    print("I'll stay home.")
I'll go to the forest.

In this case, Python evaluates the first condition to False and goes to the second condition. This condition is True, so it prints out I'll go to the forest. and stops the execution.

If neither of the two conditions is met, then it’ll print out I’ll stay home.

Of course, you can use whatever number of elif statements you want. Let’s add more conditions and also change what is printed out under the else statement to Weather not recognized. (for example, if tomorrow is “f”, we don’t know what it means).

# Several elif conditions
tomorrow = "snowy"

if tomorrow == "warm":
    print("I'll go to the sea.")
elif tomorrow == "very hot":
    print("I'll go to the forest.")
elif tomorrow == "snowy":
    print("I'll build a snowman.")
elif tomorrow == "rainy":
    print("I'll stay home.")
else:
    print("Weather not recognized.")
I'll build a snowman.

Guess what’s printed out?

Multiple Conditions

Let’s now add some complexity. What if we want to meet multiple conditions in one if statement?

Let’s say we want to predict a biome (i.e., desert or tropical forest) based on two climate measurements: temperature and humidity. For example, if it’s hot and dry, then it’s a hot desert, but if it’s cold and dry, then it’s an arctic desert. You can see that we cannot classify these two biomes based only on their humidity (they are both dry) so we also have to add the temperature measure.

In Python, we can use logical operators (i.e., and, or) to use multiple conditions in the same if statement.

Look at the code below.

# Biome prediction with and logical operator
humidity = "low"
temperature = "high"

if humidity == "low" and temperature == "high":
    print("It's a hot desert.")
elif humidity == "low" and temperature == "low":
    print("It's an arctic desert.")
elif humidity == "high" and temperature == "high":
    print("It's a tropical forest.")
else:
    print("I don't know!")
It's a hot desert.

The output will be It's a hot desert. because only when humidity is low and temperature is high, the combined condition is True. It’s not sufficient to have only one of the conditions to be True.

Formally, Python checks if the first condition of humidity is True (indeed, it is), then it checks if the second condition of temperature is True (and it is) and only in this case the combined condition is True. If at least one of these conditions isn't met, then the combined condition evaluates to False.

What if we want either of two (or more) conditions is met? In this case we should use the or logical operator.

Let’s look at an example. Say you have a list of numbers from 1 to 14 (inclusive), and you want to extract all the numbers that are smaller than 3 or greater or equal to 10. You can achieve the result using an or operator!

# or logical operator
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
nums_less_3_greater_equal_10 = []

for num in nums:
    if num < 3 or num >= 10:
        nums_less_3_greater_equal_10.append(num)

print(nums_less_3_greater_equal_10)
[1, 2, 10, 11, 12, 13, 14]

Output: [1, 2, 10, 11, 12, 13, 14]

Here Python checks whether the current number in the for loop is less than 3, and if it’s True, then the combined if statement evaluates to True. The same happens if the current number is equal to or greater than 10. If the combined if statement is True, then the expression is executed and the current number is appended to the list nums_less_3_greater_equal_10.

For the sake of experiment, let’s change or to and.

# Change or to and
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
nums_less_3_greater_equal_10 = []

for num in nums:
    if num < 3 and num >= 10:
        nums_less_3_greater_equal_10.append(num)

print(nums_less_3_greater_equal_10)
[]

Output: []

In this case, the current number should be simultaneously smaller than 3 and greater or equal to 10, which is clearly not possible so the combined if statement evaluates to False and the expression isn't executed.

To make things even more clear, look at this print statement.

print(False or True)
True

Output: True

Here Python evaluates the combination of False and True, and since we have the or logical operator, it’s sufficient that at least one of these Booleans is True to evaluate the combined statement to True.

Now, what happens if we change or to and?

print(False and True)
False

Output: False

Both Booleans should be True to evaluate the combined condition to True. Since one of them is False, the combined condition is also False. This is what happens in the example with numbers.

You can even combine multiple logical operators in one expression. Let’s use the same list of numbers, but now, we want to find all the numbers that are either smaller than 3 or greater or equal to 10 and simultaneously are even numbers.

We will be using the # More complex logical statements nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] nums_less_3_greater_equal_10_multiple_2 = [] for num in nums: if (num < 3 or num >= 10) and num nums_less_3_greater_equal_10_multiple_2.append(num) print(nums_less_3_greater_equal_10_multiple_2)

[2, 10, 12, 14]

Output: [2, 10, 12, 14]

Why is the first number of the output 2? In the second for loop, 2 is evaluated in the first condition in parentheses. It is smaller than 3, so the combined condition in parentheses is True. 2 is also divisible by 2 with the remainder 0, so the second condition is also True. Both conditions are True, so this number is appended to the list.

Why do we use parentheses? It’s because of the operator precedence in Python. What if we remove them?

# More complex logical statements without parentheses
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
nums_less_3_greater_equal_10_multiple_2 = []

for num in nums:
    if num < 3 or num >= 10 and num
        nums_less_3_greater_equal_10_multiple_2.append(num)

print(nums_less_3_greater_equal_10_multiple_2)
[1, 2, 10, 12, 14]

Output: [1, 2, 10, 12, 14]

We have 1 in the list! In Python, all operators are evaluated in a precise order. For example, the and operator takes precedence over the or operator. But if we place the or operator in parentheses, it’ll take precedence over the and operator.

First we evaluate the conditions on both sides of the and operator (it has precedence). 1 is neither greater than 10 nor yields 0 if divided by 2, so the combined condition is False. We are left with the condition if num < 3 or False. 1 is smaller than 3, so the first condition is True. The condition becomes True or False. We have an or operator, so the combined condition evaluates to True, and 1 is appended to the list. Practice by checking what happens with the other numbers.

Finally, have a look at this truth table to understand how logical operators work. Here, we will describe only the and and or logical operators, but in Python, we also have the not operator. We invite you to learn more about it and practice using it inside if statements.

Input A Input B AND OR
False False False False
True False False True
False True False True
True True True True

We have two inputs, A and B, that can be either True or False. For example, in the second row, A is True, while B is False; thus, A AND B evaluate to False but A OR B evaluate to True. The rest of the table is read in the same way. Take a minute to understand what it tells you.

Nested if Statements

Python is a very flexible programming language, and it allows you to use if statements inside other if statements, so called nested if statements. Let’s look at an example.

# Nested if statements
mark =  85

if mark >= 60 and mark <= 100:
    if mark >= 90:
        print("You are the best!")
    elif mark >= 80:
        print("Well done!")
    elif mark >= 70:
        print("You can do better.")
    else:
        print("Pass.")
elif mark > 100:
    print("This mark is too high.")
elif mark < 0:
    print("This mark is too low.")
else:
    print("Failed.")
Well done!

Output: Well done!

Here, if the mark is between 60 and 100, the expression under the if statement is executed. But then we have other conditions that are also evaluated. So, our mark is 85, which is between 60 and 100. However, 85 is smaller than 90, so the first nested if condition is False, and the first nested expression isn't executed. But 85 is higher than 80, so the second expression is executed and “Well done!” is printed out.

Of course, we also have elif statements outside the expression below the first if statement. For example, what if the mark is higher than 100? If the first condition (number between 60 and 100) is False, then we go directly to the elif statement mark > 100 and print out This mark is too low..

Try to assign different numbers to the mark variable to understand the logic of this code.

Pattern Matching in Python 3.10

The pattern matching was added in Python 3.10, released in October, 2021. In short, it can be seen a different syntax for if..elif statements. Let's look at an example by rewrting a previous example using the pattern matching.

# Previous example
tomorrow = "snowy"

if tomorrow == "warm":
    print("I'll go to the sea.")
elif tomorrow == "very hot":
    print("I'll go to the forest.")
elif tomorrow == "snowy":
    print("I'll build a snowman.")
elif tomorrow == "rainy":
    print("I'll stay home.")
else:
    print("Weather not recognized.")
I'll build a snowman.
# Pattern matching with match..case syntax
tomorrow = "snowy"

match tomorrow:
    case "warm":
        print("I'll go to the sea.")
    case "very hot":
        print("I'll go to the forest.")
    case "snowy":
        print("I'll build a snowman.")
    case "rainy":
         print("I'll stay home.")
    case _:
        print("Weather not recognized.")
I'll build a snowman.

We can see similarities between using the if..elif statements and the match..case syntax. First, we define what variable we want to match, and when we define the cases (or values this variable can take). The rest of the code is similar. If a case is matched (that's equivalent of a double equal sign), then the print expression is executed.

Note the last case statement, it's the _ case, which is equivalent to else: if no cases are matched, then we print Weather not recognized.

pass Statement

As you start writing more complex code, you may find yourself in the situation where you have to use a placeholder instead of the code you want to implement later. The pass statement is this placeholder. Let’s look at an example with and without the pass statement.

# Without pass
num = 3
if num == 3:

print("I'll write this code later.")
  Input In [24]
    print("I'll write this code later.")
    ^
IndentationError: expected an indented block after 'if' statement on line 3

Output:

File "", line 4
    print("I'll write this code later.")
    ^
IndentationError: expected an indented block

Python expects some code under the if statement, but you are yet to implement it! You can write pass there and solve this problem.

# With pass
num = 3
if num == 3:
    pass

print("I'll write this code later.")
I'll write this code later.

Output: I'll write this code later.

If instead you place pass in the if statement, Python won’t throw any error and will pass to any code you have below the if statement. This works even if you have other conditions below the first if statement.

# With pass
num = 4
if num == 3:
    pass
elif num == 4:
    print("The variable num is 4.")
else:
    print("The variable num is neither 3 nor 4.")
The variable num is 4.

Output: The variable num is 4.

Conclusions

In Python, if statements are used all the time, and you’ll find yourself using them in basically any project or script you're building, so it's essential to understand the logic behind them. In this article, we’ve covered the most important aspects of if conditions in Python:

  • Creating basic if statements
  • Adding complexity by using else and elif statements
  • Combining multiple conditions in one if statement using logical operators (or, and)
  • Using nested if statements
  • Using pass statements as placeholders

With this knowledge, you can now start working with conditional statements in Python.

Feel free to connect with me on LinkedIn and GitHub. Happy coding!

Dataquest

About the author

Dataquest

Dataquest teaches through challenging exercises and projects instead of video lectures. It's the most effective way to learn the skills you need to build your data career.

Learn data skills for free

Headshot Headshot

Join 1M+ learners

Try free courses