Decision-making is the heart of algorithmic computing. A computer program is rarely a linear sequence of instructions; it must evaluate real-time data and take appropriate action. The if statement is the simplest decision-making structure in Python. It executes a designated block of code only if a given Boolean test condition evaluates to True.
Figure 17.1: Python conditional branching flow showing decision diamonds leading to true/false execution blocks.
Unlike C, C++, or Java which wrap control blocks in curly braces {}, Python enforces whitespace indentation:
if test_condition:
# 4 spaces of indentation
statement_1
statement_2
# Practical Example:
age = 20
if age >= 18:
print("Eligibility: You are an adult eligible to vote in elections.")
print("Please ensure your voter card is registered.")
print("This line always executes (outside if block).")
In Python, you do not need to compare explicitly with == True. Every object has an inherent Boolean truth value:
cart = ["Laptop", "Mouse"]
# Pythonic condition: Checks if collection is non-empty!
if cart:
print(f"You have {len(cart)} items in your shopping cart.")
# Falsy example:
unread_messages = 0
if not unread_messages:
print("Your inbox is all caught up!")
False, the entire indented block beneath the if statement is completely skipped, and program execution continues with the next statement following the indented block.