Python Conditional Statements: if-else, elif, nested if statements

The decision control statements are usually jumped from one part of the code to another depending on whether a particular condition is satisfied or not. It allows you to execute statements, these type of decision control statements are called Conditional Statements. In Python, there are four types of Conditional Statements are exists.

  • If Statement
  • If-else statement
  • Nested if statements
  • if-elif-else statement
  • 1. If Statement : An if statement is a selection control statement based on the value of a given Boolean expression. An if statement may include 1 or n statements enclosed within the if block. At first the test condition is evaluated, if the test condition is TRUE, then the statements of if block are executed. If the test condition is FALSE, then if then the statements of if block will be skipped and the execution will jump to another statement. It has the following syntax :

    if (test condition):
      statement1
      ..........
      statement n
     statement x
    

    2. If-else statement : If-else statement is a vital role in conditional statements. At first the test condition is evaluated, if the test condition is TRUE, then the statements of if block are executed. else if test condition is FALSE, then the statements of else block are executed. It has the following syntax :

    if (test condition):
      statement1
    else:
      statement2
    

    3. Nested if Statements : To perform more complex checks, if statements can be nested and it can be placed one inside the othe . Nest if statements are used to check if more than one condition is satisfied. It has the following syntax :
    if (test condition1):
      statement1
    if (test condition2):
      statement2
      ..........
    if (test condition n):
      statement n 
    

    4. if-elif-else statement : In Python, here a special type conditional statement are supported and that is if-elif-else statement, it is used to test additional conditions apart from the initial test condition. The elif statement is a shortcut to if and else statements. It has the following syntax :
    if (test condition1):
      statement1
    elif (test condition2):
      statement2
      ..........
    elif (test condition n):
      statement n
    else:
      statement n