In this Python tutorial, we will learn about If Conditional statement, its syntax, and how to write if statements in programs, using some example scenarios.
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.
Syntax
The syntax of Python If conditional statement is
if <condition> :
statement(s)
If the condition is True, then the statements inside if block execute, else the execution continues with rest of the statement, if any.
Flowchart
The flow chart that depicts the execution flow of If statement in Python is
Examples
1. 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.
Python Program
a = 5
b = 6
if a * b == 30:
print('Hello World!')
print('The product of two numbers is 30.')
Output
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.
Python Program
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.")
Output
File "example.py", line 7
print("Inside if condition block")
^
IndentationError: unexpected indent
2. 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
.
Python Program
n = 6
if n%2 == 0:
print(f'{n} is even number.')
Output
6 is even number.
Similarly, we can print a message if the number is odd.
Python Program
n = 5
if n%2 != 0:
print(f'{n} is odd number.')
Output
5 is odd number.
Conclusion
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.