Python If

Python If Conditional Statement is used to execute a set of statements (present inside if block) when a specific condition is satisfied. If the condition is not satisfied, the statements in the if block are not executed.

In this tutorial, we will learn the syntax of Python If Conditional statement, and how to write if statements in Python program, using some example scenarios.


The syntax of Python If conditional statement is

if <condition> :

If the condition is True, then the statements inside if block execute, else the execution continues with rest of the statement, if any.


The flow chart that depicts the execution flow of If statement in Python is

Python If Statement Flowchart


Check If Product of Two Numbers is 30

In the following program, we write an If statement with the condition that the product of the two numbers a and b is equal to 30.

a = 5
b = 6

if a * b == 30:
    print('Hello World!')
    print('The product of two numbers is 30.')
Try Online


Hello World!
The product of two numbers is 30.

Please note the indentation or alignment of the statements inside the if-block. Unlike programming languages like Java or C where the statements are enclosed in curly braces, python considers the alignment of statements as block representation.

If the alignment is missed out as shown in the below program, interpreter throws IndentationError.

number_1 = 5
number_2 = 6

# observe the indentation for the statements in the if block
if number_1 * number_2 == 30:
    print("The condition is true.")
     print("Inside if condition block")
    print("statement in if loop")

print("Outside if condition block.")
Try Online


File "", line 7
    print("Inside if condition block")
IndentationError: unexpected indent

Check if Number is Even

In this example, we will take an integer in variable n, and print if n is even using If statement in Python.

The condition for our if statement would be to check if n leaves a reminder of zero when divided by 2.

n = 6

if n%2 == 0:
    print(f'{n} is even number.')
Try Online


6 is even number.

Similarly, we can print a message if the number is odd.

n = 5

if n%2 != 0:
    print(f'{n} is odd number.')
Try Online


5 is odd number.


In this Python Tutorial, we have seen the syntax of If conditional statement in Python, a pictorial representation of working of if statement, an example and how the indentation of the statements in an if block should be, and IndentationError if we miss out indentation.