How to use if elif and else in python
To create a multiple conditional statement in Python, we use the if, elif, and else statements.
if (condition 1):
statement 1
elif (condition 2):
statement 2
elif (condition 3):
statement 3
else:
statement 4
If condition 1 is true, the program executes instruction 1.
Otherwise, it checks the following conditions 2 and 3 in the elif clauses until it finds a true condition.
If no condition is true, the program executes the condition in the else clause.
Note that the elif clauses are optional, and there can be 2, 3, or more of them, or none at all. The else clause is also optional. When the program finds a true condition, it executes the block of statements and exits the conditional structure without checking the other conditions.
All statements must begin with an indent to the right of the if, elif, or else statements (indentation).
Instructions can also be blocks consisting of several instructions.
Example
This control structure checks the value of the variable age under multiple conditions.
if age>7 and age<=10:
print(">7-10")
elif (age<=3):
print("1-3")
elif (age<=5):
print("4-5")
elif (age<=7):
print("6-7")
else:
print("error")
The output of the program changes according to the value of the variable age.
If the value of the variable is equal to 8, 9 or 10
>7-10
If it is less than or equal to 3 the first elif is executed
1-3
If it is less than or equal to 5 the second elif is executed
4-5
If it is less than or equal to 7 the third elif is executed
6-7
If none of the above conditions are true, the program executes the block of statements in the else clause and the output is "error".
error