Python if…else Statement

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.

Note that, if-else statement is used to code the same way you would use it in the English language.

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

1

2

3

4

if(condition):

block_of_code_1 forwhen condition isTRUE

else:

block_of_code_2 forwhen condition isFALSE

The if..else statement evaluates condition and will execute body of if only when test condition is True.

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

1

2

3

4

5

6

7

8

# Program checks if the number is even or odd

# And displays an appropriate message

num=8

ifnum%2==0:

print("Even Number")

else:

print("Odd Number")

When you run above program, the output will be following:

1

Even Number

In the above example, when num is divided by 2 and gets remainder equal to 0, then the condition is true and body of if is executed and body of else is skipped.

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.