Python If-Then-Elif-Else Statement

Advertisements
Advertisements

 24 total views

In previous two articles, we discussed conditional statements such as if and if-then-else. All of those previous structures are using one conditions only, what if, we want to check multiple conditions at different time and make decisions based on the output of those conditions. The python has a special if-then-elif-else construct to check multiple conditions one after another. Look at the figure below to understand this logic better.

Python If-Else-Elif-Else
Python If-Else-Elif-Else

The first condition, condition 1 is the if-block and if true then executes the block A and if false will move to the next condition, which is condition 2.If condition 2 is true that will execute block B and if it is false then move to condition 3. The condition 3 if true will execute the block C and if everything is false, the final output is block D.

Note that the condition 1 comes from if-block, condition 2 comes from elif, condition 3 is elif and else block is D.

Example – If-then-elif-else

In this example, student receive his grade in A, B, C , D , E, and F.

Advertisements

A = Excellent

B = Outstanding

C = Very Good

D = Good

E = Fair

F = Fail.

We need to print the result based on the grade that the student gets. Consider the following code.

grade = input("Enter Your Grade:" )
if grade == "A":
    print("You grade is Excellent!")
elif grade == "B":
    print("Your grade is Outstanding!")
elif grade == "C":
    print("Your grade is Very Good!")
elif grade == "D":
    print("Your grade is Good!")
elif grade == "E":
    print("Your grade is Fair..Work Hard!")
elif grade =="F":
    print("Your Failed.. Try again later")
else:
    print("Wrong Input")
          

The output of the program is given below.

Output – If-then-elif-else

=========== RESTART: C:/Python_projects/Display_Student_Result.py ===========
Enter Your Grade:D
Your grade is Good!
>>> 

Bestseller

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.


Advertisements
Advertisements
Advertisements