How to use 'if...else' condition in Python

About the 'if...else' condition in Python

In Python, the 'if...else' conditional statement is used for conditional execution of a block of code out of two alternative blocks of code.

If the condition of 'if' is true, the block of code under 'if' statement will be executed.

Alternatively, if the condition of 'if' 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 condition.

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

Syntax of 'if...else' condition

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

A block of code is placed under 'if' condition which will be executed if the 'if' condition is true.

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

A block of code is placed under 'else' statement which will be executed if the 'if' condition is false.

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

Using 'if...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. You know that the condition is not true as 10 is greater than 9.

3. Now create a block of code that will be executed if the 'if' condition is true. In the following example, the message print("Yes, x is greater than 10") will be printed.

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

In the following example, the 'else' code block will be executed as the 'if' condition is false.

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

Please take a closer look at the following example:

Example of 'if...else' condition

Output of the above example
No, x is not greater than 10

Live Code Playground

In the following Python code editor, you can practice the above code by creating 'if...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