Skip to main content

Python if...elif....else Statement

The elif is short for else if. It allows us to check for multiple expressions.

if…elif…else are conditional statements that provide you with the decision making that is required when you want to execute code based on a particular condition. When you run into a situation where you have several conditions, you can place as many elif conditions as necessary between the if condition and the else condition.

The elif statement allows you to check multiple expressions for TRUE and execute a block of code as soon as one of the conditions evaluates to TRUE.

If the condition for if is False, it checks the condition of the next elif block and so on. If all the conditions are False, the body of else is executed. Only one block among the several if...elif...else blocks is executed according to the condition.

Syntax:

>>>if (condition):
         Statement
>>>elif(condition):
          Statement
>>>else(condition):
         Statement

Flow Chart:

python if elif else statement

Example:

x = 5
if x % 2 == 0:
    print('x is divisible by 2')
elif x % 3 == 0:
    print('x is divisible by 3')
else:
    print('x is neither divisible by 2 nor by 3 ')

Output:

x is neither divisible by 2 nor by 3
Tags
Submitted by devanshi.srivastava on June 7, 2021

Devanshi, is working as a Data Scientist with iVagus. She has expertise in Python, NumPy, Pandas and other data science technologies.

About

At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.