Python If-Then-Else Statement


 3 total views

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 else-block. 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.

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

Example – if-then-else

Let us take out previous example of cash available to purchase an item with price and 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 
     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.


Python Programming: Using Problem Solving Approach

Python Programming is designed as a textbook to fulfil the requirements of the first-level course in Python programming. It is suited for undergraduate degree students of computer science engineering, information technology as well as computer applications. This book will enable students to apply the Python programming concepts in solving real-world problems. The book begins with an introduction to computers, problem solving approaches, programming languages, object oriented programming and Python programming. Separate chapters dealing with the important constructs of Python language such as control statements, functions, strings, files, data structures, classes and objects, inheritance, operator overloading and exceptions are provided in the book. Each chapter ends with objective-type questions, review questions, programming and debugging exercises to facilitate revision and practice of concepts learnt.