Conditional Statements


Python conditional statements are used to perform different actions based on different conditions.

In python, we do not need to use the parentheses for the block level code instead indentation is used to declare a block.

If 2 statements are at the same indentation level then they are the part of the same block.

Generally, 4 spaces are given to indent the statements.

Python includes following forms of conditional statements:

  1. if statement
  2. else statement
  3. elif statement

1. if Statement

The if statement is used when we want to execute some statements when the specified condition is true. Remember the colon after the test condition.

Syntax:

    if condition:
        # statements to be executed if the condition is true

Example:

    if 10 < 20:
    	print(“Welcome to TutorialsDuniya.com”)



2. else Statement

The else statement is used to execute the statements when the condition specified in if statement is false.

Syntax:

    if condition:
        # statements to be executed if the condition is true
    else:
        # statements to be executed if the condition is false

Example:

    if 20 < 15:
        print(“20 is less than 15”)
    else:
        print(“20 is not less than 15”)


3. elif Statement

The elif statement is used to test multiple conditions and execute the specific block of statements depending upon the condition.

An elif statement must be succeeded by an if statement.

Syntax:

    if condition1:
        # statements to be executed if the condition is true
    elif condition2:
        # statements to be executed if the condition is true
    elif condition3:
        # statements to be executed if the condition is true
    else:
        # statements to be executed if the condition is true

Example:

    if num==10:
        print(“number is 10”)
    elif num==20:
        print(“number is 20”)
    elif num==50:
        print(“number is 50”)
    else:
        print(“number is not equal to 10,20 or 50”)