In the previous article, you learned about the if-block and how it execute 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
Consider the following diagram. In the figure, if the condition is true, execute block A (also call it if-block) and if the condition is false, execute block B.
Example – if-then-else
Let us take out previous example of
cash available to purchase an item with
tax. If the
price + tax is less than the
cash 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 + tax is less than the cash available. It is not true because the total amount is 5200. Therefore, the program jump into the second block. the else block and prints “Insufficient funds”.
Note the indentation for the else block also. All line within a block has the same indentation.