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.
The if-elif-else statement used in Python helps automate that decision making process. Python if-elif-else
if (condition):
statement
elif (condition):
statement
.
.
else:
statement
if:
age = 18
if (age >= 18):
print("You are eligible for Vote")
You are eligible for Vote
if-else:
The else keyword introduces a code block which is executed if and only if all previous if and elif conditionals are False.
age = 18
if (age >= 18):
print("You are eligible for Voting")
else:
print("You are not eligible for Voting")
You are not eligible for Voting
if-else-elif :
The elif keyword is always followed by a conditional expression and must follow a previous if or elif statement. it introduces a code block which is executed only if all previous if or elif conditions are false and the current conditional is True.
number = 3
if (number == 1):
print("number is 1")
elif (number == 2):
print("number is 2")
elif (number == 3):
print("number is 3")
else:
print("number is not present")
Number is 3
In the above example line 7 is only executed when the input is equal to 3.
Line 5 is only executed if the condition on line 3 is False and the condition on line 4 is True.
Remember that elif is a shorthand for else if but in Python to write the above without elif with the same logic you will need to do either:
- The if-elif-else statement used in Python helps automate that decision making process.
- 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.