Python If Else

Python If Else – Basic idea of an if else condition block is that, when the condition is satisfied, the statements in the if block are executed, and when the condition is not satisfied, the statements in the else block are executed.

In this tutorial, we will learn the syntax of if-else statement, how to write an if-else statement with a condition, with the help of example Python programs.

Syntax

The syntax of if-else statement is

if <condition>:
    statement(s)
else:
    statement(s)

where condition could be an expression that evaluates to a boolean value.

Flowchart

The working of if-else statement in Python is shown in the following picture.

Python If Else Statement - Python Tutorial - www.tutorialkart.com
Python If Else Statement

Example

In this example, we will write an if-else statement where the condition checks if given number is even.

example.py – Python Program

n = 4

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

Output

4 is even number.

Note : Observe the indentation and alignment of the statements inside the if-block or else-block. Unlike programming languages like Java or C programming, where the statements are enclosed in curly braces, Python considers the alignment of statements as block representation.

Now, let us take a value for n, such that the condition becomes false.

example.py – Python Program

n = 3

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

Output

3 is odd number.

Since we have taken a value for n such that the condition n%2 == 0 becomes false, the statement(s) inside else block were executed.

Conclusion

In this Python Tutorial, we have learnt if-else conditional statement, and how any statement in if or else block could be another if or if-else conditional statements.