if, elif, and else in python

In this tutorial you will learn how to use conditions using if in python. You will also learn how to use elif and else statements in python.

If in python

If statement in python is used by using if keyword. If statement is used to make decisions based on specific condition.

Example:

x = 10
y = 5

if x > y:
    print('x is greater than y.')

Output:

x is greater than y.

Elif in python:

elif is used to make another condition. elif is used in scenarios like if previous condition is not true then try this condition. elif condition gets checked if the condition in if statement is false.

Example:

x = 10
y = 20

if x > y:
    print('x is greater than y.')
elif y > x:
    print('y is greater than x.')

Output:

y is greater than x.

else in python:

else condition is used to execute something when conditions from if statement and elif statements are not true.

Example:

x = 5
y = 5

if x > y:
    print('x is greater than y.')
elif y > x:
    print('y is greater than x.')
else:
    print('x and y are equal.')

Output:

x and y are equal.

Example of if, elif and if statement:

marks = 60
if marks >= 60:
    print('You got distinction in exam.')
elif marks >= 55:
    print('You got first class in exam.')
elif marks >= 50:
    print('You got second class in exam.')
elif marks >= 40:
    print('You passed in exam.')
else:
    print('You failed in exam.')

Output:

You got distinction in exam.

Conclusion:

In this article, you learned how to use if, elif and else statements in python. If you have problems while implementing code, you can ask me through the comment section.

Check out Recommended Posts:

Loops in python

Functions in python

Lists in python

Tuples in python

Dictionary in python

Leave a Reply

Your email address will not be published. Required fields are marked *