Python Conditional Statements: If_else, Elif, Nested If Statement

This Python if statement video tutorial explains if-else, elif, nested if, and elif ladder statements in Python with programming examples:

When we consider our real-time scenario every day, we make some decisions and based on the decisions made we will take further actions. Hence all our daily life activities depend on the decisions we make.

A similar situation arises in the programming language as well where we have to make some decisions and based on that the program will execute.

Python provides four conditional statements. In this tutorial, we will learn about conditional statements with brief descriptions, syntax, and simple examples for each of these conditional statements.

Learn core Python from this series of Python Tutorials.

Python if Statements

Python If Statement Video Tutorials

Conditional Statements in Python: If_else, elif, Nested if:

Conditional Statements in Python and PyCharm Installation:

Installation Of Pycharm

Pycharm is a free – open source tool which is available in different platforms like Windows, Linux, and Mac. You can also use other platforms like PyDev, Visual Studio Code, Sublime, etc.

  • Download Pycharm community edition from the below link Pycharm.
  • Follow the on-screen instruction to install the Pycharm.
  • Once PyCharm is installed, then create a project.
  • To create a project go to File ->New Project-> provide the project name and click on create.

Conditional Statements In Python

In programming languages, most of the time in large projects we have to control the flow of execution of our program and we want to execute some set of statements only if the given condition is satisfied, and a different set of statements when it’s not satisfied.

Conditional statements are also known as decision-making statements. We need to use these conditional statements to execute the specific block of code if the given condition is true or false.

In Python we can achieve decision making by using the following statements:

  • if statements
  • if-else statements
  • elif statements
  • Nested if and if-else statements
  • elif ladder

In this tutorial, we will discuss all the statements in detail with some real-time examples.

#1) if statements

Python if statement is one of the most commonly used conditional statements in programming languages. It decides whether certain statements need to be executed or not. It checks for a given condition, if the condition is true, then the set of code present inside the ” if ” block will be executed otherwise not.

The if condition evaluates a Boolean expression and executes the block of code only when the Boolean expression becomes TRUE.

Syntax:

If ( EXPRESSION == TRUE ):
     Block of code
else:
     Block of code

Here, the condition will be evaluated to a Boolean expression (true or false). If the condition is true, then the statement or program present inside the ” if ” block will be executed and if the condition is false, then the statements or program present inside the “else” block will be executed.

Let’s see how it looks on a flow chart.

if_statement_flowchart

Python if statement

If you observe the above flow-chart, first the controller will come to an if condition and evaluate the condition if it is true, then the statements will be executed, otherwise the code present outside the block will be executed.

Let’s see some examples of ” if ” statements.

Example: 1

num = 5
if (num < 10):
        print(“Num is smaller than 10”)

print(“This statement will always be executed”)

Output: Num is smaller than 10.

This statement will always be executed.

if statements example1_output

In the above example, we declared a variable called ‘Num’ with the value as 5 and the ” if ” statement is checking whether the number is lesser than 10 or not. If the condition is true then a set of statements inside the if block will be executed.

Example: 2

a = 7
b = 0
if (a > b):
            print(“a is greater than b”)

Output:

a is greater than b

if statements example2_output

In the above example, we are checking the relationship between a and b using the greater than (>) operator in the if condition. If “a” is greater than “b” then we will get the above output.

Example: 3

a = 0
b = 7
if (b > a):
           print(“b is greater than a”)

Output:

b is greater than a.

if statements example3_output

Example: 4

a = 7
b = 0
if (a):
              print(“true”)

Output:

true

if statements example4_output

If you observe, in the above example, we are not using or evaluating any condition in the “if” statement. Always remember that in any programming language, the positive integer will be treated as true value and an integer which is less than 0 or equal to 0 will be treated as false.

Here the value of a is 7 which is positive, hence it prints true in the console output.

Example: 5

if (‘Python’ in [‘Java', ‘Python’, ‘C#’]):
     print(“true”)

Output:

true

if statements example5_output

Here, we are verifying if the element ‘Python’ is present in the given list or not. Hence it prints true because “ Python “ is present in the given list.

Let’s take one real-life example where we will use the Python if statement.

For Example: You have written an exam for a total score of 100 and if your score is above or equal to 60 then you will be considered as PASS in the exam.

Let’s write the code for it.

Example: 6

passing_Score = 60
my_Score = 67
if(my_Score >= passing_Score):
             print(“Congratulations! You have passed your exam”)

Output:

Congratulations! You have passed your exam.

if statements example6_output

Remember to use the (:) operator at the end of the if statement, because whatever the code you write after the colon operator will be a part of “if block” and indentation is very important in Python.

Example: 7

passing_Score = 60
my_Score = 67
if(my_Score >= passing_Score):
             print(“You passed the exam”)
print(“Congratulations!”)

Output:

You passed the exam

Congratulations!

if statements example7_output

Here, print(“Congratulations!”) statement will always be executed even though the given condition is true or false.

The problem with the above code is the statement ‘print(“Congratulations!”)’ will always be executed even if the condition is evaluated to true or false. But in real-time, if you pass the exam or if you fail in the exam, then the system will say Congratulations!!!.

In order to avoid this, Python provides one conditional statement called if-else.

#2) if-else statements

The statement itself says if a given condition is true then execute the statements present inside the “if block” and if the condition is false then execute the “else” block.

The “else” block will execute only when the condition becomes false. It is the block where you will perform some actions when the condition is not true.

if-else statement evaluates the Boolean expression. If the condition is TRUE then, the code present in the “ if “ block will be executed otherwise the code of the “else“ block will be executed

Syntax:

If (EXPRESSION == TRUE):
        Statement (Body of the block)
else:
        Statement (Body of the block)

Here, the condition will be evaluated to a Boolean expression (true or false). If the condition is true then the statements or program present inside the “if” block will be executed and if the condition is false then the statements or program present inside the “else” block will be executed.

Let’s see the flowchart of if-else

if-else_statement_flowchart

if-else statements flowchart

If you observe the above flow chart, first the controller will come to if condition and evaluate the condition if it is true and then the statements of if block will be executed otherwise “else” block will be executed and later the rest of the code present outside “if-else” block will be executed.

Example: 1


num = 5
if(num > 10):
     print(“number is greater than 10”)
else:
     print(“number is less than 10”)

print (“This statement will always be executed” )

Output:

number is less than 10.

This statement will always be executed.

if-else statements example1_output

In the above example, we have declared a variable called ‘num’ with the value as 5 and in the “if” statement we are checking if the number is greater than 5 or not.

If the number is greater than 5 then, the block of code inside the “if” block will be executed and if the condition fails then the block of code present inside the “else” block will be executed.

Example: 2

a = 7
b = 0
if (a > b):
           print(“a is greater than b”)
else:
           print(“b is greater than a”)

Output:

a is greater than b

if-else statements example2_output

In the above code if “a” is greater than “b” then the statements present inside the “if” block will be executed and the statements present inside the “else” block will be skipped.

Example: 3

a = 7
b = 0
if (a < b):
            print( “a is smaller than b” )
else:
            print( “b is smaller than a” )

Output:

b is smaller than a

if-else statements example3_output

In the above code, “a” is smaller than “b”, hence statements present inside the “else” block will be executed and statements present inside the “if” block will be skipped.

Now let’s take a real-time example.

Example: 4

passing_Score = 60
my_Score = 67
if(my_Score >= passing_Score):
             print(“Congratulations! You passed the exam”)    
             print("You are passed in the exam")        
else:
             print(“Sorry! You failed the exam, better luck next time”)

Output:

Congratulations! You passed the exam

You are passed in the exam

if-else statements example4_output

Example: 5

passing_Score = 60
my_Score = 47
if(my_Score >= passing_Score):
             print(“Congratulations! You passed the exam”) 
             print("You are passed in the exam")
else:
             print(“Sorry! You failed the exam, better luck next time”)

Output:

Sorry! You failed the exam, better luck next time

if-else statements example5_output

#3) elif statements

In Python, we have one more conditional statement called “elif” statements. “elif” statement is used to check multiple conditions only if the given condition is false. It’s similar to an “if-else” statement and the only difference is that in “else” we will not check the condition but in “elif” we will check the condition.

“elif” statements are similar to “if-else” statements but “elif” statements evaluate multiple conditions.

Syntax:

if (condition):
            #Set of statement to execute if condition is true
elif (condition):
            #Set of statements to be executed when if condition is false and elif condition is true
else:
       #Set of statement to be executed when both if and elif conditions are false

Example: 1


num = 10
if (num == 0):
     print(“Number is Zero”)

elif (num > 5):
       print(“Number is greater than 5”)

else:
       print(“Number is smaller than 5”)

Output:

Number is greater than 5

elif statements example1_output

In the above example we have declared a variable called ‘num’ with the value as 10, and in the “if” statement we are checking the condition if the condition becomes true. Then the block of code present inside the “if” condition will be executed.

If the condition becomes false then it will check the “elif” condition if the condition becomes true, then a block of code present inside the “elif” statement will be executed.

If it is false then a block of code present inside the “else” statement will be executed.

Example: 2

num = -7
if (num > 0):
              print(“Number is positive”)
elif (num < 0):
              print(“Number is negative”)
else:
              print(“Number is Zero”)

Output:

Number is negative

elif statements example2_output

In the above example, first, we are assigning the value 7 to a variable called num. The controller will come to the “if” statement and evaluate the Boolean expression num > 0 but the number is not greater than zero hence if block will be skipped.

As the if condition is evaluated to false the controller will come to the “elif” statement and evaluate the Boolean expression num < 0, hence in our case number is less than zero hence ‘Number is negative’ is printed.

In case both the “if” and “elif” condition is evaluated to false then a set of statements present inside the “else” block will be executed.

#4) Nested if-else statements

Nested “if-else” statements mean that an “if” statement or “if-else” statement is present inside another if or if-else block. Python provides this feature as well, this in turn will help us to check multiple conditions in a given program.

An “if” statement is present inside another “if” statement which is present inside another “if” statements and so on.

Nested if Syntax:

if(condition):
           #Statements to execute if condition is true
           if(condition):
                    #Statements to execute if condition is true
           #end of nested if
#end of if

The above syntax clearly says that the if block will contain another if block in it and so on. If block can contain ‘n’ number of if block inside it.

Let’s look at the nested if-else statement

Nested if-else statements flowchart

Example: 1


num = 5
if(num >0):
       print(“number is positive”)

if(num<10):
       print(“number is less than 10”)

Output:

number is positive

number is less than 10

Nested if-else statements example1_output

In the above example, we have declared a variable called ‘num’ with the value as 5.

First, it will check the first “if” statement if the condition is true, then the block of code present inside the first “if” statement will be executed then it will check the second “if” statement if the first “if” statement is true and so on.

Example: 2

num = 7
if (num != 0):
              if (num > 0):
                            print(“Number is greater than Zero”)

Output:

Number is greater than Zero

Nested if-else statements example2_output

Here, the controller will check if the given number is not equal to Zero or not, if the number is not equal to zero then it enters the first if block and then in the second if block it will check if the number is greater than Zero or not, if it’s true then the control enters the nested if block and executes the statements and leaves the block and terminates the program.

Example: 3

i = 10
if (i == 10): 
      if (i < 20): 
      print (i, "is smaller than 20") 
      if (i < 21): 
      print (i, "is smaller than 21") 

Output:

10 is not smaller than 20
10 is smaller than 21

Nested if-else statements example3_output

Nested if-else Syntax:

if(condition):
           #Statements to execute if condition is true
           if(condition):
                     #Statements to execute if condition is true
           else:
                    #Statements to execute if condition is false
else:
            #Statements to execute if condition is false

Here we have included the “if-else” block inside an if block, you can also include an “if-else” block inside “else” block.

Example: 4

num = -7
if (num != 0):
          if (num > 0):
                      print(“Number is positive”)
           else:
                      print(“Number is negative”)
else:
           print(“Number is Zero”)

Output:

Number is negative

Nested if-else statements example4_output

#5) elif Ladder

We have seen about the “elif” statements but what is this elif ladder? As the name itself suggests a program that contains a ladder of “elif” statements or “elif” statements are structured in the form of a ladder.

This statement is used to test multiple expressions.

Syntax:

if (condition):
            #Set of statement to execute if condition is true
elif (condition):
             #Set of statements to be executed when if condition is false and elif condition is true
elif (condition):
             #Set of statements to be executed when both if and first elif condition is false and second elif condition is true
elif (condition):
              #Set of statements to be executed when if, first elif and second elif conditions are false and third elif statement is true
else:
       #Set of statement to be executed when all if and elif conditions are false

Example: 1

my_marks = 90
if (my_marks < 35):
              print(“Sorry!, You failed the exam”)
elif(my_marks > 60 and my_marks > 100): 
              print(“Passed in First class”)
else:
              print(“Passed in First class with distinction”)

Output:

Passed in First class with distinction

elif Ladder example1_output

The above example describes the elif ladder. Firstly the control enters the “if” statement and evaluates the condition if the condition is true then the set of statements present inside the if block will be executed else it will be skipped and the controller will come to the first elif block and evaluate the condition.

A similar process will continue for all the remaining “elif” statements and in case all if and elif conditions are evaluated to false then the else block will be executed.

Python If Statement In One Line

In Python, we can write “if” statements, “if-else” statements and “elif” statements in one line without worrying about the indentation.

We know we can write “if” statements as shown below

Syntax:

if (condition):
         #Set of statements to execute if condition is true

In Python, it is permissible to write the above block in one line, which is similar to the above block.

Syntax:

if (condition): #Set of statements to execute if condition in true

There can be multiple statements as well, you just need to separate it by a semicolon (;)

Syntax:

if (condition): statement 1; statement 2; statement 3;…;statement n

If the condition is true, then execute statement 1, statement 2 and so on up to statement n.

In case if the condition is false then none of the statements will be executed.

Example: 1

num = 7
if (num > 0): print(“Number is greater than Zero”)

Output:

Number is greater than Zero

if-else in One line example1_output

Example: 2

a = 10
if (a): print( " The given value of a: " ); print(a)

Output:

The given value of a: 10

if-else in One line example2_output

If-else Statements In One Line

Syntax:

if (condition):
           #Set of statement to execute if condition is true
else:
            #Set of statement to execute if condition is false

The above if-else block can also be written as shown below.

Syntax:

if (condition): #Set of statement to execute if condition is true
else: #Set of statement to execute if condition is false

There can be multiple statements as well, you just need to separate it by a semicolon (;)

Syntax:

if (condition): statement 1; statement 2; statement 3;…;statement n
else: statement 1; statement 2; statement 3;…;statement n

Example: 1

num = 7
if (num > 0): print(“Number is greater than Zero”)
else: print(“Number is smaller than Zero”)

Output:

Number is smaller than Zero

if - else statements in One line example1_output

Example: 2

if (‘a’ in ‘fruits’): print(“Apple”); print(“Orange”)
else: print(“Mango”); print(“Grapes”)

Output:

Mango
Grapes

if - else statements in One line example2_output

Elif Statements In One Line

Syntax:

if (condition):
           #Set of statement to execute if condition is true
elif (condition1):
             #Set of statement to execute if condition1 is true
else:
             #Set of statement to execute if condition and condition1 is false

The above elif block can also be written as below.

Syntax:

if (condition): #Set of statement to execute if condition is true
elif (condition1): #Set of statement to execute if condition1 is true
else: #Set of statement to execute if condition and condition1 is false

There can be multiple statements as well, you just need to separate it by a semicolon (;)

Syntax:

if (condition): statement 1; statement 2; statement 3;…;statement n
elif (condition): statement 1; statement 2; statement 3;…;statement n
else: statement 1; statement 2; statement 3;…;statement n

Example: 1

num = 7
if (num < 0): print("Number is smaller than Zero")
elif (num > 0): print("Number is greater than Zero")
else: print("Number is Zero")

Output:

Number is greater than Zero

elif Statements in One Line example1_output

Example: 2

if (‘a’ in ‘fruits’): print(“Apple”); print(“Orange”)
elif (‘e’ in ‘fruits’): print(“Mango”); print(“Grapes”)
else: print(“No fruits available”)

Output:

elif Statements in One Line example2_output

Multiple Conditions In If Statements

It’s not that you can only write one condition inside an “if” statement, we can also evaluate multiple conditions in an “if” statement like below.

Example: 1

num1 = 10
num2 = 20
num3 = 30
if (num1 == 10 and num2 == 20 and num3 == 30):
             print(“All the conditions are true”)

Output:

All the conditions are true

Multiple Conditions in if Statements example1_output

Here, in the “if” statement we are checking multiple conditions using AND operator, which means if all the conditions are true only when the statements inside an if block will be executed.

We can also specify the OR operators as well.

Example: 2

fruitName = “Apple”
if (fruitName == “Mango” or fruitName == “Apple” or fruitName == “Grapes”):
              print(“It’s a fruit”)

Output:

It’s a fruit

Multiple Conditions in if Statements example2_output

Here, in an “if” statement out of three conditions, only one condition is true as that’s the rule of the OR operator. If any one condition is true then the condition will become true and the statement present inside the if block will be executed.

Let’s consider a real-time scenario to find the number of days present in a month and we know that during a leap year the number of days will change. We will see this in a programmatic way using “if, elif and else” statements.

Example: 3

currentYear = int(input (" Enter the year: " ) )
month = int(input("Enter the month: " ) )
if ((currentYear % 4 ) == 0 and (currentYear % 100 ) != 0 or (currentYear % 400 ) == 0 ):
       print("Leap Year")
       if(month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12):
               print("There are 31 days in this month " )
       elif ( month == 4 or month == 6 or month == 9 or month == 11 ):
       print("There are 30 days in this month " )
       elif ( month == 2 ):
       print("There are 29 days in this month " )
       else:
       print("Invalid month ")
elif ( ( currentYear % 4 ) != 0 or ( currentYear % 100 ) != 0 or ( currentYear % 400 ) != 0 ):
       print("Non Leap Year " )
       if ( month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12 ):
       print("There are 31 days in this month" )
       elif ( month == 4 or month == 6 or month == 9 or month == 11 ):
       print("There are 30 days in this month " )
       elif ( month == 2 ):
       print("There are 28 days in this month ")
       else:
       print("Invalid month " )
else:
       print( " Invalid Year " )

Output: 1

Enter the year: 2020
Enter the month: 4

Leap Year
There are 30 days in this month

Multiple Conditions in if Statements example3_output

Frequently Asked Questions

Q #1) Can we write else if statements in one line Python?

Answer: Yes, we can use if-else in one line. In Python, we can convert if-else into one conditional statement.

Refer to the example below:
num = 7
output = ‘Greater than 0’ if num > 0 else ‘Smaller than 0’
print(output)The output will be: Greater than 0

Q #2) How do you write if-else statements in Python?

Answer: Python has some conditional statements about which two are if and else. Without any doubt, if we talk about the large programs then, these two statements are most commonly used in all the programming languages. Basically, using “ if “ and “ else “ we set some conditional in our program.
Basic syntax:

if (condition):
// Body of “ if ”

else:
// Body of “ else ”

Q #3) What are elif statements in Python?

Answer: “elif” statement is used where we have a lot of conditional statements between “ if “ and “ else ”. To avoid the use of multiple “ if “ statements we consider “ elif” to be used. The program will check all the written conditions if the “ elif “ statement will be true then, the block of code under the statement will be executed.

Q #4) What does “ == “ mean in Python?

Answer: This “ == “ is known as the “comparison” operator. It will return TRUE if the items are equal to each other and return FALSE if not.

For example:

a = 12
b = 12

if( a == b )
print( “ The value of a is equal to b: “, a, “ = ”, b)
else:
print( “ The values are not matching! “ )

The output will be: “ The value of a is equal to b: 12 = 12

Q #5) What does Python “pass” do?

Answer: The “pass” keyword will act as a space for future code in the program. If it gets executed, nothing will happen and will give no output. It is used because empty functions, loops, and classes are not allowed in the programming. For this Python develops the keyword which we can use if we don’t know what to write in the particle function or class but can be used for future use.

For example:

def demo( ):
{
pass
}

The output will be nothing.

Conclusion

In this Python if statement tutorial, we learned about Conditional Statements in Python. These are the statements that alter the control flow of execution in the program. We have different types of conditional statements like if, if-else, elif, nested if, and nested if-else statements which control the execution of our program.

Python if statement evaluates a boolean expression to true or false, if the condition is true then the statement inside the if block will be executed in case if the condition is false then the statement present inside the else block will be executed only if you have written the else block otherwise it will do nothing.

We have one more statement called elif statement where the else statement is combined with an if statement, which executes depending on the previous if or elif statements.

PREV Tutorial | NEXT Tutorial