How to use if condition in Python

About the if 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 condition in an if statement is evaluated in a boolean context (either 'True' or 'False').

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 condition must be indented consistently.



Syntax of if condition

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

Statement of code block must have at least one space for indentation.

Using if 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 > 5: where x is greater than 5 is the condition. The condition (x > 5) is followed by a colon (:) which is part of the syntax.

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

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, 9 is greater than 5


Using if with multiple conditions in Python

The if condition may have multiple conditions which are combined by logical operators ('and', 'or', 'not').

Creating if multiple conditions:

1. Create an if multiple conditions like this if c < 9 and a > b: where the first condition is 'c < 9' and the second condition is 'a > b'. Two conditions are combined using 'and' operator. (a = 9, b = 7, and c = 8 as in the following example)

2. Create a block of code print("Yes, c is less than 9 and a is greater than b") that will be executed if the both conditions are true.

In the following example of 'or', the if multiple conditions if c < 9 or a > b: are combined by 'or' operator. The block of code print("Yes, c is less than 9 or a is greater than b") will be executed if either 'c < 9' or 'a > b' condition is true.

Please take a closer look at the following examples:

Example of if multiple conditions

Output of the above example
Yes, c is less than 9 and a is greater than b
Yes, c is less than 9 and a is greater than b

Live Code Playground

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