Python If-Then-Elif-Else Statement

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.

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

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

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

Advertisements

Example – If-then-elif-else

In this example, student receive his grade in A, \hspace{3px} B,\hspace{3px}  C , \hspace{3px} D , \hspace{3px} E, and F.

\begin{aligned}
&A = Excellent\\
&B = Outstanding\\
&C = Very \hspace{3px}Good\\
&D = Good\\
&E = Fair \\
&F = Fail
\end{aligned}

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!
>>> 

Advertisements

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.