Skip to main content
HomeAbout PythonLearn Python

if…elif…else in Python Tutorial

Learn how you can create if…elif…else statements in Python.
Updated Dec 2022  · 4 min read
Read the Spanish version 🇪🇸 of this article.

if…elif…else are conditional statements that provide you with the decision making that is required when you want to execute code based on a particular condition.

The if…elif…else statement used in Python helps automate that decision making process.

Run and edit the code from this tutorial online

Open Workspace

if condition

The if condition is considered the simplest of the three and makes a decision based on whether the condition is true or not. If the condition is true, it prints out the indented expression. If the condition is false, it skips printing the indented expression.

if condition:
    expression

Example of if

Suppose you have a variable z, equal to 4. If the value is 'even', you will print z is 'even'. You will use modulo operator 2, which will return 0 if z is 'even'. As soon as you run the below code, Python will check if the condition holds. If True, the corresponding code will be executed.

z = 4

if z % 2 == 0:  # True
    print("z is even")
z is even

Example of multiple lines inside if statement

It is perfectly fine to have more lines inside the if statement, as shown in the below example. The script will return two lines when you run it. If the condition is not passed, the expression is not executed.

z = 4
if z % 2 == 0:
    print("checking" + str(z))
    print("z is even")
checking 4
z is even

Example of a False if statement

Let's change the value of z to be odd. You will notice that the code will not print anything since the condition will not be passed, i.e., False.

z = 5
if z % 2 == 0:  # False
    print("checking " + str(z))
    print("z is even")

if-else condition

The if-else condition adds an additional step in the decision-making process compared to the simple if statement. The beginning of an if-else statement operates similar to a simple if statement; however, if the condition is false, instead of printing nothing, the indented expression under else will be printed.

if condition:
    expression
else:
    expression

Example of if-else

Continuing our previous example, what if you want to print 'z is odd' when the if condition is false? In this case, you can simply add another condition, which is the else condition. If you run it with z equal to 5, the condition is not true, so the expression for the else statement gets printed out.

z = 5
if z % 2 == 0:
    print("z is even")
else:
    print("z is odd")
z is odd

if-elif-else condition

The most complex of these conditions is the if-elif-else condition. When you run into a situation where you have several conditions, you can place as many elif conditions as necessary between the if condition and the else condition.

if condition:
    expression
elif condition:
    expression
else:
    expression

Example one of if-elif-else condition

Below is an example of where you want different printouts for numbers that are divisible by 2 and 3.

Here, since z equals 3, the first condition is False, so it goes over to the next condition. The next condition does hold True. Hence, the corresponding print statement is executed.

z = 3
if z % 2 == 0:
    print("z is divisible by 2")
elif z % 3 == 0:
    print("z is divisible by 3")
else:
    print("z is neither divisible by 2 nor by 3")
z is divisible by 3

Example two of if-elif-else condition

In the below example, you define two variables room and area. You then construct if-elif-else and if-else conditions each for room and area, respectively.

In the first condition, you check if you are looking in the kitchen, elif you are looking in the bedroom, else you are looking around elsewhere. Depending on the value of the room variable, the satisfied condition is executed.

Similarly, for the area variable, you write an if and else condition and check whether the area is greater than 15 or not.

# Define variables
room = "bed"
area = 14.0

# if-elif-else construct for room
if room == "kit":
    print("Looking around in the kitchen.")
elif room == "bed":
    print("Looking around in the bedroom.")
else:
    print("Looking around elsewhere.")

# if-elif-else construct for area
if area > 15:
    print("Big place!")
else:
    print("Pretty small.")

When we run the above code, it produces the following result:

Looking around in the bedroom. Pretty small.

Try it for yourself.

To learn more about elif statements in Python, please see this video from our course, Intermediate Python.

This content is taken from DataCamp’s Intermediate Python course by Hugo Bowne-Anderson.

Topics

Python courses

Certification available

Course

Intermediate Python

4 hr
1M
Level up your data science skills by creating visualizations using Matplotlib and manipulating DataFrames with pandas.
See DetailsRight Arrow
Start Course
See MoreRight Arrow
Related

A Deep Dive into the Phi-2 Model

Understanding the Phi-2 model and learning how to access and fine-tune it using the role-play dataset.
Abid Ali Awan's photo

Abid Ali Awan

12 min

Python List Size: 8 Different Methods for Finding the Length of a List in Python

Compare between 8 different methods for finding the length of a list in Python.
Adel Nehme's photo

Adel Nehme

8 min

An End-to-End ML Model Monitoring Workflow with NannyML in Python

Learn an end-to-end workflow to monitor any model in your Jupyter notebook in production environments.
Bex Tuychiev's photo

Bex Tuychiev

15 min

How to Delete a File in Python

File management is a crucial aspect of code handling. Part of this skill set is knowing how to delete a file. In this tutorial, we cover multiple ways to delete a file in Python, along with best practices in doing so.
Amberle McKee's photo

Amberle McKee

5 min

Finding the Size of a DataFrame in Python

There are several ways to find the size of a DataFrame in Python to fit different coding needs. Check out this tutorial for a quick primer on finding the size of a DataFrame. This tutorial presents several ways to check DataFrame size, so you’re sure to find a way that fits your needs.
Amberle McKee's photo

Amberle McKee

5 min

Exploring the Python 'Not Equal' Operator

Comparing values in Python to check if they are not equal is simple with the not equal operator. Check out this quick tutorial on how to use the not equal Python operator, as well as alternatives for comparing floats.
Amberle McKee's photo

Amberle McKee

5 min

See MoreSee More