Python If Else

Python If-Else Statement

Python If Else is used to implement conditional execution where in if the condition evaluates to true, if-block statement(s) are executed and if the condition evaluates to false, else block statement(s) are executed.

Python If-Else is an extension of Python If statement where we have an else block that executes when the condition is false.

Syntax of Python If-Else Statement

The syntax of Python if-else statement is given below.

if boolean_expression:
    statement(s)
else:
    statement(s)
Run this program

Observe the indentation for the lines after if keyword and else keyword. if and else are in line of indentation while the statements inside if block and else block are in next possible indentation.

Example 1: Python If Else with Condition True

In the following example, we have a condition that will evaluate to true and the statement(s) of if block are executed.

Python Program

a = 2
b = 4

if a<b:
	print(a, 'is less than', b)
else:
	print(a, 'is not less than', b)
Run this program

Output

2 is less than 4

2<4 returns True, and hence the if block is executed.

Example 2: Python If Else with Condition False

In the following if-else statement, we have a condition that will evaluate to false and the statement(s) of else block are executed.

Python Program

a = 5
b = 4

if a<b:
	print(a, 'is less than', b)
else:
	print(a, 'is not less than', b)
Run this program

Output

5 is not less than 4

5<4 returns False, and hence the else block is executed.

Example 3: Python Nested If Else

You can have nested if-else statements, i.e., if-else statement inside an if-else statement. After all, if-else is just another Python statement.

Python Program

a = 2
b = 4
c = 5

if a<b:
	print(a, 'is less than', b)
	if c<b:
		print(c, 'is less than', b)
	else:
		print(c, 'is not less than', b)
else:
	print(a, 'is not less than', b)
Run this program

Output

2 is less than 4
5 is not less than 4

Thus using nested if-else statements, you could implement a complex business login in your Python application.

Summary of Python If-Else

In this tutorial of Python Examples, we learned what an if-else statement does in Python, how to write an if-else statement, and scenarios like nested if-else statements, all with the help of well detailed examples.