In the previous article, you learned about the
and how it executes statement if the condition for the
is true. But we have not discussed anything about what should happen when
is false.
The python programming language have a separate block of code to execute when the
is false. It is called the
. Consider the following diagram. In the figure, if the condition is true, execute
(also call it
) and if the condition is false, execute
.

Example – if-then-else
Let us take out previous example of
to purchase an item with
and
. If the
is less than the
, 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
is less than the cash available. It is not true because the total amount is
. Therefore, the program jumps into the second block. the else block and prints
. Note the indentation for the else block also. All line within a block has the same indentation.