Table of Contents
Toggle
Python’s decision-making functionality relies on if..elif...else statements. The if keyword requires a boolean expression, followed by a colon (:), which starts an indented block. Statements with the same level of indentation execute if the boolean expression in the if statement evaluates to True. If the expression is False, the interpreter bypasses the indented block and proceeds to execute statements at the previous indentation level.
Python provides several types of decision-making statements, which help execute different blocks of code based on conditions.
else block if the if condition is False.if or else if statement inside another if statement.
If an if clause consists of a single line, it can be written inline with the header statement.
var = 100
if (var == 100): print("Value of expression is 100")
print("Good bye!")
If the condition in the if statement is True, the corresponding block executes; otherwise, the else block runs.
var = 100
if (var == 100):
print("Value of var is equal to 100")
else:
print("Value of var is not equal to 100")
A nested if statement allows multiple conditions to be checked sequentially.
var = 100
if (var == 100):
print("The number is equal to 100")
if var % 2 == 0:
print("The number is even")
else:
print("The given number is odd")
elif var == 0:
print("The given number is zero")
else:
print("The given number is negative")
Mastering decision-making in Python enables you to write efficient and readable programs. Understanding if, if...else, and nested if statements is crucial for implementing logic in Python applications.
