Python elif statement with examples

The elif statement

In the previous chapter, we learnt how to use Python if and if…else for one or two different options. What if you have multiple situations and one of those needs to be executed?

The elif Python statement allow us to use it for multiple conditions and run only one block of statement that evaluates as true. Other programming languages like Java, C# generally use the else..if statement for this purpose.

Note: There is no Python else if for multiple conditions. Instead, you have to use Python elif statement.

Syntax of elif in Python

Following is the general syntax of elif statement:

if condition:

statement(s) to be executed

elif condition2:

statement(s) to be executed

else:

statement(s) to be executed

Example of using elif

Following example shows how to use the Python elif statement to use multiple conditions.

Note that, the first statement is still Python if statement followed by two elif blocks and finally using the else block. If none of the conditions evaluates as true the else block will be executed.

Output

3rd elif block is executed

As you can see, first we declared a variable. After that, the if statement is given which is followed by two elif statements. As variable num1 value is 3, the 2nd elif block will be true and the statement inside it will be executed.

Also, just like the simple if or if..else statements, indentation is used to execute the statements in the elif statement. If you do not use indentation, it will be considered outside of the block and may result in some error.

Was this article helpful?

Related Articles

Leave A Comment?