Python if else statement

By | July 18, 2019

Python if else statement is another form of Python if statement. It executes one block of statements, if the given condition is true and the other when it is false. So there are two blocks in if else statement – if-block and else-block.

Syntax of Python if else Statement

if condition:
    if-block
else:
    else-block
Where if-block is a set of one or more statements indented properly. Similarly, else-block is also a set of one or more statements indented properly as shown above.

Flow chart

Python if else statement syntax example working flow chart

Working

First of all the given condition is evaluated. If it is true, if block will be executed otherwise else block is executed.

First Example of if else statement

Write an if else statement to check a number is even or odd:

num=10
if num%2==0:
    print('Even')
else:
    print('Odd')
print('Thanks')
The first statement assigns a value 10 to num variable. The Second statement is an if else statement. Therefore, the given condition is checked. It gives a true result because the remainder operator % gives a zero. When we divide 10 by two, the quotient is 5 and remainder is a 0. Therefore, if-block is executed, and it prints ‘Even’ on the screen. The third statement is a print(‘Thanks’) statement. It is not included in else-block, since we have removed the indentation. So it prints ‘Thanks’ on the screen

Now, let us change the value of num variable to 11.
num=11
if num%2==0:
    print('Even')
else:
    print('Odd')
print('Thanks')

The first statement assigns a value 11 to num variable. The Second statement is an if else statement. Therefore, the given condition is checked. It gives a false result because the remainder operator % gives a 1. When we divide 11 by two, the quotient is 5 and remainder is a 1. Therefore, if else statement will ignore if-block and execute else-block. Hence, it prints ‘Odd’ on the screen. The third statement is a print(‘Thanks’) statement. It is not included in else-block, since we have removed the indentation. So it prints ‘Thanks’ on the screen

Python-if-else-output

Leave a Reply

Your email address will not be published. Required fields are marked *