Python: If, Elif & Else Statements

python programs

if, elif and else statements in python allow us to perform different tasks depending on certain conditions.

These are also known as conditional statements because they decide which statements should run and which should not.

Verbally: “Hey, if this happens then perform this action.”

Syntax:

The general syntax of if, elif and else statements is as follows:

if <condition1>:
    perform this statement1
elif <codition2>:
    perform this statement2
elif <codition3>:
    perform this statement3
...
else:
    perform this last statement

Here, the elif and else statements are optional. You use them when you want some other statements or code to execute when the condition in the if block doesn’t satisfy, otherwise, you can use single if statement alone.

You can also write multiple elif statements like in the above example to execute different set of statements under different conditions. But there can be only one else statement at the end of one group of if-else logic.

Let’s see some examples to have better understanding of if, elif, and else statements in Python.

Examples using if and else

Example 1: if and else

Let’s say if a student passes the examination if he or she gets more than or equal to 40 marks otherwise fails. This is how you can represent it in python using if and else:

if marks >= 40:
    print("Pass")
else:
    print("Fail")

Example 2: if with True condition

if True:
    print("This is Inside of IF")

Output: This is Inside of IF

Example 3: if, elif and else

x=3
if x==2:
    print("value of x is 2")
elif x==3:
    print("value of x is 3")
else:
    print("value of x is not matching")

Output: value of x is 3

Example 4: if with multiple elif

def greet(role):
     if role == "prime minister":
         print("Hello Sir!")
     elif role == "soldier":
         print("Yes Sir!")
     elif role == "programmer":
         print("I can hack NASA with HTML!")
 greet("programmer")

Output: I can hack NASA with HTML!

Characteristics of if-else in Python

  • The if statement allows the program to perform some action depending on the specified condition.
  • Only a single elif statement in order of a group of if-else statements executes, if all the above conditions are false.
  • The else statement executes only if all the above conditions (including if and elif ) are false.

Tip: Use if-elif-else when only one of the given tasks/statements should need to be executed depending on certain conditions.

Leave a Reply

Your email address will not be published. Required fields are marked *