Python If-Elif-Else Conditional Statements with Examples

Python Tutorial Series: Using if-elif-else conditional statements.

Rohit Kumar Thakur
Python in Plain English
5 min readOct 25, 2021

--

Python Tutorial Series

Hello Developers, in the last article I talked about Python if-else conditional statement and we practised some really good examples. In the if-else conditional statement, we have only two conditions. If the first condition is true then execute the first statement or if the condition is not true then execute the other (else condition) statement. But what if we have multiple conditions, then how do we deal with that? Don’t worry, Python has one solution to this problem.

Attention all developers seeking to make social connections and establish themselves while earning passive income — look no further! I highly recommend ‘From Code to Connections’, a book that will guide you through the process. Don’t miss out, grab your copy now on Amazon worldwide or Amazon India! You can also go for Gumroad

We are going to use an if-elif-else conditional statement to deal with such problems. Don’t worry if you are new to Python’s conditional statements. When we deal with some nice examples then it will all be clear to you.

Let’s start with an example. In this example, we are going to assign grades to the students based on marks obtained:

Range         Grade[90, 100]       A
[70, 89] B
[50, 69] C
[40, 49] D
[0, 39] F

You have to take the marks of the student as input from the user. Then assign the grades based on marks obtained by the students.

The code of the problem stated is here:

print("Grade List")
print ("==========")
def gradeAssign(marks):
assert marks>=0 and marks<=100

if marks>=90:
grade="A"
elif marks>=70:
grade="B"
elif marks>=50:
grade="C"
elif marks>=40:
grade="D"
else:
grade="F"

return grade

def main():
marks = float(input('Enter your marks: '))
print("Marks: ", marks, "\nGrade: ", gradeAssign(marks))

main()

The output of the above Python program is:

>>> Grade List
==========
Enter your marks: 91
Marks: 91.0
Grade: A
>>> Grade List
==========
Enter your marks: 68.2
Marks: 68.2
Grade: C
>>> Grade List
==========
Enter your marks: 33
Marks: 33.0
Grade: F

Here I used a Python function to do the job. The main function is called (at the end) so it will execute first. In the main function, first, I take marks as an input from the user, these marks will be in float form. Because some of the students might get marks something like “65.5”, “83.7”, “88.2”, and so on. Therefore we can’t use the int function here. The float function will do our job. Next, I print the marks obtained and call the gradeAssign() function for grades.

In the gradeAssign() function, I used the assert statement. In Python, the assert statement is used to continue the execution, if the given condition evaluates to True. If the assert condition evaluates to False, then it raises the AssertionError exception with the specified error message. Here the condition is that the marks will be in the range of 0 to 100. If the user input marks below 0 and above 100 then the python program will throw an exception AssertionError.

Next, I used the conditional statement. If the marks obtained are greater than “90” then the grade will be “A”. Else if (elif) the marks obtained are greater than “70” then the grade will be “B”. Continue this until we reach the condition of grade “F”. One thing you may notice is that we don’t have to specify any statement for else conditions. If all the conditions of if and elif fail, then the function will automatically execute the else conditional statement.

You can practice more questions here:

Python Code To Check If The Year Is A Leap Year

Palindrome Program In Python

Least Common Multiple (LCM) in Python

Python Function to Check If a Number is Prime or Not

Program to Find Out the Maximum of Three Numbers

Determine A Given Natural Number Is A Perfect Number Or Not Using Python

Greatest Common Divisor or HCF In Python

Print Hollow Rectangle or Square in Python

General Form of if-elif-else Conditional Statement

if  < condition1 >:
< Statement s1 to be executed >
elif < condition2 >:
< Statement s2 to be executed >
elif <condition3 >:
< Statement s3 to be executed >
.
.
.
.
else:
< Statement s(n) to be executed >

Flow Diagram of if-elif-else Conditional Statement

Flow Diagram of Python if-elif-else Conditional Statement

Nested if-elif-else Conditional Statement

Sometimes, we need a control structure within another control structure. Such a mechanism is called nesting.

We will understand this with an example. In this example, we are going to find out the maximum of three numbers. This means, we are going to take input of three numbers from the user and our program will tell which of the number is maximum. Simple, right?

Let’s start the code:

print("Find the maximum Number")
print ("==========")
def FindMaximum(n1,n2,n3):
if n1>n2:
if n1>n3:
maxNumber=n1
else:
maxNumber=n3
elif n2>n3:
maxNumber=n2
else:
maxNumber=n3
return maxNumber
def main():
n1 = int(input("Enter first number: "))
n2 = int(input("Enter Second numer: "))
n3 = int(input("Enter Third number: "))

maximum = FindMaximum(n1,n2,n3)
print("Maximum number is", maximum)

main()

The output of the program is:

>>> Find the maximum Number
==================
Enter first number: 65
Enter Second numer: 5646
Enter Third number: 6166
Maximum number is 6166
>>> Find the maximum Number
==================
Enter first number: 45
Enter Second numer: 56
Enter Third number: 65
Maximum number is 65

BINGO. We got the maximum number. In the main function, we got the input of three numbers from the user and redirected the input numbers to the FindMaximum() function. In the FindMaximum() function, we are using nested conditional statements.

If the condition (n1>n2) is true then we enter the nested conditional statement. If the condition (n1>n2) is false then our program will check for other conditional statements. Now, inside the nested control structure, if the first number is greater than the third number then the first number is the maximum, else the third number is maximum. Assume some random numbers and try to fit on the control structure, you will get a more clear picture.

Well, That’s it for this article. In the next article, we will talk about Python For Loop.

If this article sounds informative to you then make sure to follow and share it with your geek community.

Hello, My Name is Rohit Kumar Thakur. I am open to freelancing. I build React Native projects and I am currently working on Python Django. Feel free to contact me at (freelance.rohit7@gmail.com).

More content at plainenglish.io

--

--