If-elif statement in Python Programming

If-elif Statement in Python: If-elif statement is also the most important and easiest concept of control flow statements. This statement is very helpful, while or when we need to make the decision(when we have more than one condition to check) based on our problem what to do next(in our life).

  • The same type of problem arises sometimes in our programming also where we have to execute our code based on these decision making statements.

Let’s suppose we take an example: We have three numbers 1, 2 & 3, now we have said to write a program to check which number is greater, Now in that case we use if-elif statements. Greatest of three number.

We will learn about these flow control statements in detail.

if-elif statement in python

Other flow control statements are also there, These are given below:-

  • if (already discussed)
  • if-else (already discussed)
  • if-elif
  • if-elif-else
  • nested-if

Let’s discuss all the above statements in detail one by one:- If and if-else statements we have discussed already, followed by this article (if-statement, if-else statement), now we discuss if-elif:

(i). If-elif statement: The execution of the if-elif statement is different than our previous control statements that we have discussed so far. If-elif statement returns the given result or output depending upon the input. Especially, when we have to check multiple conditions then we prefer to use if-elif statements.

Note: Point to be noted is that, in if-elif statements, if the first condition is True it execute the block of code inside the True condition & if the first one condition is False and the second one is True then it will execute the block of code inside the second condition, But what if both of the condition is not True. “Yes” in that case it will not return any result or output. Same as if-statement.

Syntax

x = 23
if(x==22):
    print("True")
elif(x==21):
   print("False")
elif(x==23):
   print("Yes")

# output
# Yes

The above given example is the easiest example to understand the if-elif statement. The only difference between the if-else and if-elif statement is that the if-else statement only shows the output as True if the condition is True & False if a condition is False. But if-else returns output in more than two conditions. I hope this statement has been clear by the above given example. If you still have doubt, please refer to above given example again:

Example:

#if statement example 

x = 18 
if(x==23):
   print("True") 
elif(x==22):
   print("False")
elif(x==20): 
   print("Yes")

# output
# It will not display any result.

Example 2: Write a program to print the greater between two numbers.

Hint 1
a = 34
b = 30
a is greater

Hint 2
a = 25
b = 30
b is greater

a = 34
b = 30
if ( a > b ):
    print("a is greater")
elif ( b > a ):
    print("b is greater")

# output
# a is greater

 

Other Control Flow Statements: