if-elif in python

If-else In Python

If-else in python used to check conditions. These statements are also used to make decisions.

before we move further have a quick look at comparison operators, which we will use in if-else statements.

Comparison Operators

Equal to==a == b
Not equal to!=a != b
Greater than>a > b
Less than<a < b
Greater than or equal to>=a >= b
Less than or equal to
<=a <= b

There are 7 Types of operators in python including conditional operators.

Now, Let’s have a look at syntax :

If-elif-else syntax

This is the syntax of if-elif-else statement.

#If Statement
if condition:
#elif Statement
elif condition:
#Else Statement

Flowchart of If-elif-else

This is the flowchart of how this conditional statement(if-elif-else) works.

If-else In Python

Quick Example

Think, you have to validate the number. Here are the conditions :

  • If number is 5, print “Number is 5”
  • Number is less than 5, print “Number is less than 5”
  • Number is greater than 5 , print “Number is greater than 5”

And here is the code :

#Initial variable "number" and it's value is 5
number = 5

if number < 5:
    print("Number is less than 5")
elif number == 5:
    print("Number is 5")
    print("Number is greater than 5")

Explanation :

  1. Here we first take a variable “number” and give it a value 5
  2. Then we started with if statement which has a condition number < 5, if it will be true then print statement will execute, otherwise it will check for elif statement.
  3. Now condition number == 5 will true then print statement of elif statement will be execute otherwise else statement will execute.

This is a quick example of if-elif and else statement.

Nested if-else Statement in Python

If we have if-elif-else in another if-elif-else then it called nested in programming

Let’s have a look ate example,

number = int(input("Enter Number :"))

if number >= 0:
    if number == 0:
        print("Number is Zero")
        print("Number is greater then 0")
    print("Number is Negative")

Here we used input() function which is in-built in python and it is used for taking input from user.


Enter Number : 5
Number is greater then 0
Enter Number : 0
Number is Zero
Enter Number : -8
Number is Negative

This is all about if-elif-else conditional statements in python.


  • Take input hour from user
  • If hour < 12 print “Good Morning”
  • If 12 < hour < 5 “Good Afternoon”
  • Else print “Good Evening”

Leave a Reply

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

You May Also Like