Skip to content
Home ยป Python If-Then-Else Statement

Python If-Then-Else Statement

    In the previous article, you learned about the if-block and how it executes statement if the condition for the if is true. But we have not discussed anything about what should happen when if-block is false.

    The python programming language have a separate block of code to execute when the if-block is false. It is called the else-block. Consider the following diagram. In the figure, if the condition is true, execute block \hspace{3px} A (also call it if-block) and if the condition is false, execute block \hspace{3px} B.

    Python If-Then-Else Block
    Python If-Then-Else Block

    Example – if-then-else

    Let us take out previous example of cash \hspace{3px} available to purchase an item with price and tax. If the price \hspace{3px} + \hspace{3px} tax is less than the cash \hspace{3px} available, a purchase can be done. Otherwise, customer cannot buy the item.

    # Declaring cash available for purchase
    cashAvailable = 5000
    # price of item with tax 
    price = 5000
    tax = 200
    # The if-block executes if the price + tax is less than or equal to cash
    if cashAvailable >= price + tax:
         print("Purchase Successful", price + tax)
    # The else will tell what to do if cash available is less 
    else:
         print("Insufficient Cash ! Purchase cannot be done!")
    print("Transaction Complete!")

    The output of the program will be as follows.

    Insufficient Cash! Purchase cannot be done!
    Transaction Complete!

    The program first check if price \hspace{3px} + \hspace{3px} tax is less than the cash available. It is not true because the total amount is 5200. Therefore, the program jumps into the second block. the else block and prints "Insufficient \hspace{3px} funds". Note the indentation for the else block also. All line within a block has the same indentation.