Python If Else

Python If-Else Statement

Python If Else statement is used to implement conditional execution where in if the condition evaluates to True, if-block statement(s) are executed or 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 If-Else

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

if boolean_expression:
    statement(s)
else:
    statement(s)

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

Examples

1. 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 Code Copy

Output

2 is less than 4

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

2. 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 Code Copy

Output

5 is not less than 4

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

3. 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 Code Copy

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

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.

Related Tutorials

Code copied to clipboard successfully 👍