if elif Statement in Python Programming
Decision Making in Python
In this lesson, we will understand what if elif statement is and how it works in Python programming along with some example.
What is if elif Statement
Here, a user can decide among multiple options. The if statements in Python program are executed from the top down. As soon as one of the conditions controlling the if or elif is true, the statement associated with that if or elif is executed, and the rest of the elif is bypassed. If none of the conditions is true, then the final else statement will be executed.
if elif Statement Syntax
if condition: statement elif condition: statement elif condition: statement ... else: statement
In the above syntax, you can see that we have started with if statement and then we are using elif statement. The ... means that we can write more elif statements if requires to check multiple options. If none of the conditions written inside if or elif statements are true, then the final else statement will be executed. Here else statement is optional.
Now let's see an example for more understanding.
Python program to check if an integer variable's value is equal to 10 or 15 or 20 using else if statement.
a=20 if a==10: print('value of a is 10') elif a==15: print('value of a is 15') elif a==20: print('value of a is 20') else: print('value of a is different')
value of a is 20
Here you can see that the first condition a==10 is false so the second condition a==15 written in elif statement is checked and the condition is also false, again the third condition a==20 written in the elif statement is checked and this time the condition is true, so the statement which is written below second elif statement (using tab indentation) has executed and the output is printed on the screen.
Test Your Knowledge
Attempt the practical questions to check if the lesson is adequately clear to you.