In the last tutorial we learned how to use if statements in Python. In this guide, we will learn another control statement ‘if..else’.
The if statement is used to test specified condition and if the condition is TRUE, if block executes, otherwise else block executes.
The else statement executes when the if statement is FALSE.
We use if statements when we need to execute a certain block of Python code when a particular condition is true. If..else statements are like extension of ‘if’ statements. For example, you want to print ‘even number’ if the number is even and ‘odd number’ if the number is not even, we can accomplish this with the help of if..else statement.
Syntax of if..else in Python
block_of_code_1 for when condition is TRUE
block_of_code_2 for when condition is FALSE
conditionand will execute body of
ifonly when test condition is
If the condition is
False, body of
else is executed.
Python uses Indentation to know which statement belong to which block.
Flow diagram of if..else
if..else example in Python
# Program checks if the number is even or odd
# And displays an appropriate message
num = 8
if num % 2 == 0:
ifis executed and body of
If num is not equal to 0, the condition is false and body of
else is executed and body of
if is skipped.
If num is equal to 0, the condition is true and body of
if is executed and
body of else is skipped.