IF, ELIF & ELSE In Python

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

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

if Condition

Example of if

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 we run it. If the condition is not passed, the expression is not executed.

Example of a False if Statement

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

if-else Condition

Example of if-else

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

if-elif-else Condition

Example of if-elif-else Condition

Below is an example of where we want different printouts for numbers that are divisible by 2 & 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.

Example of if-elif-else Condition

In the below example, we define two variables room & area. We then construct if-elif-& if-else conditions each for room & area, respectively.

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

Similarly, for the area variable, we write an if & else condition & check whether the areais greater than 15 or not.

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

RELATED LINKS

Data Scientist & Machine Learning Engineer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store