Python If Else, If Elif Else, Nested If Statements

The control flow statements are required to execute the program to fulfill the condition or requirements. These statements control the flow of execution of a program. There are different types of control statements used in Python and the list is given below,

  1. The decision-making statements are if, else, and elif.
  2. The looping statements are for loop, range(), and while loop.
  3. The branching statements are break and continue.
  4. The pass statement

In this tutorial, We will learn decision-making statements such as if, else, and elif.

Decision-making statements:

1. If statement:

One of the basic control flow statements is the if statement. It is used to execute a particular condition in the program. Indentation or white spaces maintain is one of the most important parts of Python programming. Any curly braces are not used in Python like other programming languages. In the case of the if statement programmer has to give full attention to the use of indentation. 

Syntax:

if (condition)
   #statement or body

2. If Else statement in Python:

It is an optional statement in the if statement. It is used to execute a false part of any condition. The else statement executes any program at least once whether the condition is false. This statement is used after the if statement. This statement cannot be used without if statement.

Syntax:

if ( condition ):
    # statement or body
else: 
    # statement or body

3. Elif statement in Python:

The elif statement is used in Python to execute multiple conditions in a program. This statement is used after the if statement. The elif statement cannot be used without an if statement. The if statement can be used single in a program but the elif statement cannot be used alone. After if statement more than one elif statement can be used. At the last else statement is used.

Syntax:

if (condition):
   #statement or body
elif ( condition ):
   #statement or body
elif ( condition ):
   #statement or body
else 
   #statement or body

4. Nested If-Else in Python

Syntax:

if Condition_1 :
    if Condition_1.1 :
        if Condition__1.1.1 :
           # Code Block 1.1.1
        else
            Indented Code Block
    elif Logical_Expression_1.2 :
        # Code Block 1.2
    else :
        # Code Block
elif Logical_Expression_2 :
    # Code Block 2
elif Logical_Expression_3 :
    # Code Block 3
...
else :
    # Code Block