How to use if elif else condition in Python

About the if elif else condition in Python

In Python, the if conditional statement is used for conditional execution. It evaluates a condition and executes a block of code if the condition is true.

The elif (short form of else if) condition is used to chain multiple conditions. When the if condition is false and you want to check more conditions, you can use elif.

When the if or elif condition is false, the block of code under 'else' statement will be executed.

These comparison operators ('<', '>', '==', '!=', '<=', '>='), logical operators ('and', 'or', 'not'), and membership tests ('in', 'not in') are commonly used for comparison in the if or elif condition.

The block of code after the 'if', elif and 'else' conditions must be indented consistently.



Syntax of if elif else condition

The 'if' will be followed by a condition with colon (:).

The 'elif' will be followed by a condition with colon (:).

The 'else' will be followed by a colon (:).

Code blocks after 'if', 'elif', and 'else' statements must have at least one space for indentation.

Using if elif else condition in Python

1. Create a variable 'x' and assign 9 to the variable x (x = 9).

2. Create an if condition using 'x' variable if x > 10: where x is greater than 10 is the condition. The condition (x > 10) is followed by a colon (:) which is part of the syntax.
Now create a block of code that will be executed if the condition is true. In the following example, the message print("Yes, x is greater than 10") will be printed.
You know that the condition is not true as 10 is greater than 9.

3. Create an elif condition using 'x' variable elif x < 10: where x is less than 10 is the condition. The condition (x < 10) is followed by a colon (:) which is part of the syntax.
Now create a block of code that will be executed if the condition is true. In the following example, the message print("Yes, x is less than 10") will be printed.
You know that the condition is true as 9 is less than 10.

5. Create an 'else:' statement with the block of code print("No, x is not greater than 10") that will not be executed as the elif condition is true.

Important! Spaces have been kept before print() function for indentation.

Please take a closer look at the following example:

Example of if condition

Output of the above example
Yes, x is less than 10

Live Code Playground

In the following Python code editor, you can practice the above code by creating if elif else conditions. Click on the 'Execute Code' button to execute the code; the executed output will be displayed in the following Python Code Output frame. Practice until you become comfortable and proficient with your code.

Python logo Python Online Editor
Python Code Output