Python If elif and else statement

    In this article we are going to learn the first concept of Flow Control and learn how to use the if, elif and else statements in Python.

    So let's get started.

    What are if and else statements?

    Python if statement

    In Python, there is a keyword if that operates on the Booleans operators such as True and False. if statement is used to decide whether to execute a specific block code.

    If statement syntax:

    if Expression:
        statement()

    the statement() will only execute if the Expression is True . First, the if statement checks whether the Expression is True or False . If the if statement found that the Expression value is True then only Python proceeds further and executes the statement() code or the code that resides in the if statement block.

    Note: Python also treats 0 and empty list, string, tuple, set and dictionary as Falsy values.

    Examples

    if True:
        print("1 This Statement will execute because the Expression is true")
    
    if False:
        print("2 this statement won't execute because the expression is False")
    
    if  0:
        print("3 this statement won't execute because the expression is False")
    
    if 2 > 3:
        print("4  this statement won't execute because 2 is not greater than 3 and it is False")
    
    if not 2>3:
        print("5 this statement will execute because 2 is not greater than three ")

    #Output

    1 This Statement will execute because the Expression is true
    5 this statement will execute because 2 is not greater than three

    In the above example, we wrote five if statements and in output, we got only two statements whose Expressions were True .

    Example 2

    age = int(input("Enter Your age: "))
    
    #execute if the age is greater than 18
    if(age>=18):
        print("You are eligible to vote")
    

    Output:

    Enter Your age: 23
    You are eligible to vote

    Python Else statement

    In case the Expression of the if statement is False and we want a different block of code to execute there we can use the else statement just after the if . An else is a statement works only if the if statement does not execute or the expression is False. This means that if the expression is False then only the else statement works.

    The else statement always corresponds to the if statement you cannot use an else statement independently if there is no if statement.

    Syntax to write an else statement

    if Expression:
        statement( if Expression is True)
    else:
        statement(if Expression is False)

    Let’s understand it with an example:

    if True:
        print("1 this statement will execute because of the if expression is True")
    else:
        print("2  this statement will not execute because its corresponds if statement is True")
    
    if 3 > 4 :
        print("3 this statement will not execute because the Expression is False ")
    else:
        print("4 this statement will execute because its correspond if statement is False ")

    #Output:

    1 this statement will execute because of the if expression is True
    4 this statement will execute because its correspond if statement is False

    Code explanation

    In the above example, we saw that only those else statements executed which if Expressions were False . I n the above example, there were 4 statements to execute but only 2 executed.

    And always remember one if statement can have only one else statement and it should be next to it.

    Example 2

    age = int(input("Enter Your age: "))
    
    #execute if the age is greater than 18
    if(age>=18):
        print("You are eligible to vote")
    else:
        print(f'You are not eligible to vote. Wait for {18-age} more years! ')
    

    Output

    Enter Your age: 17
    You are not eligible to vote. Wait for 1 more years!

    If elif and else statements:

    Till now, we have used if , and else now we will learn a new additional statement use with the if statement that is Python elif statement.

    With if...else statement we check for only one expression, if the expression is True the if executed otherwise the else execute.

    What if we have multiple expression or multiple conditions to check and wants to run only one specific block of code. In that case we use the Python elif statement.

    Using the elif statement we can check for multiple expression and run one specific block of code.

    Syntax to use an elif statement:

    if expression:
    
        statement(if expression is true)
    elif another_expression :
    
        statement(if the expression is false and another_expression is True)
    elif another_expression_2 :
    
        statement( if the expression and another_expression is False and another_expression_2 is True)
    else:
    
        statement( if all the above expression is False)

    let’s understand it with an Example:

    if 4 < 3 :
        print("the expression of if statement is False so this statement won't execute")
    elif 4 < 2:
        print(" this statement won't execute because the elif expression is False ")
    elif 2 < 4:
        print("this statement will execute because the expression of this elif statement is True")
    else:
        ("this statement will execute if all the above expressions are false")

    #Output

    this statement will execute because the expression of this elif statement is True

    Example 2

    
    [num1, num2, operation] = input("Enter number 1 number 2 and operation (eg: 30,40,+) : ").split(",")
    
    
    if operation=="+":
        result = int(num1) +int(num2)
        print(f"Addition: {num1} + {num2} = ",result )
        
    elif operation=="-":
        result = int(num1) - int(num2)
        print(f"Subtraction: {num1} - {num2} = ",result )
    
    elif operation=="*":
        result = int(num1) * int(num2)
        print(f"Multiplication: {num1} * {num2} = ",result )
    
    elif operation=="/":
        result = int(num1) / int(num2)
        print(f"Division: {num1} / {num2} = ",result )
    
    else:
        print("Operation {operation} not valid!")
    

    Ouptut

    Enter number 1 number 2 and operation (eg: 30,40,+) : 50,3,*
    Multiplication: 50 * 3 =  150

    Nested if Statements:

    The nested if statement means we are using an if statement inside the another if statement.

    When you are using the nested if statements, be careful with the indentation.

    Let’s understand it with an example

    x=40
    if x > 20:
        print("x is greater than 20 ")
        if x > 30:
            print("(nested if statement) x is greater than 30 too")
        
            if x > 40:
                print("(nested_nested  if statement) x is greater than 40 too")
            else:
                print("(nested_nested else statement) x is not greater than 40")
        
        else:
            print("(nested if statement) x is not greater than 30")
    else:
       print("x is not greater than 20")

    #Output

    x is greater than 20 
    (nested if statement) x is greater than 30 too
    (nested_nested else statement) x is not greater than 40

    Conclusion

    The Python if..elif..else statements are also known as Python conditional statements. Conditional statement because they execute a specific block of code based on the condition they receive. The conditional statement starts with if statement, the if statement work on an expression and execute its block if the expression is True . With the if statement we can also take the use of elif and else statements. Using the elif statement we can check for multiple conditions and the else statement execute a default block of code if all the expression of if and elif are False.

    Points to Remember:

    • The if statement will only execute if its expression is True.
    • If the expression is False the else statement will execute.
    • You cannot use else and elif statements without If statement
    • While using the nested if statements be careful with the indentation