Python If Else

Python

If-Else Statement in Python

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

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

 

Syntax of If-Else statement in Python

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

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

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

 

Example 1: Python If Different from True Condition

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

Python Program

a = 2
b = 4

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

Output

2 is less than 4

2<4 return THAT’S RIGHTand thus 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 else block’s statement(s) is executed.

Python Program

a = 5
b = 4

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

Output

5 is not less than 4

5<4 return Wrongand thus another block is executed.

 

Example 3: Python nested if different

You can have nested if-else statements, i.e. if-else statements 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)

Output

2 is less than 4
5 is not less than 4

Thus, by using nested if-else statements, you can implement complex business logging in your Python application.

 

Summary of Python If-Else

In this guide of Python example we have learned if-else statements in Python, how to write if-else statements and situations like nested if-else statements, all with the help of detailed examples.

Hope this helps!

Source link

Share: