Learn how to control program flow by executing specific code blocks only when a condition evaluates to True.
What it is
The if statement is the fundamental building block of decision-making in Python. It allows your program to branch: if a specified condition is true, the indented block of code following it runs; otherwise, it is skipped. This mechanism relies on boolean logic, where expressions evaluate to either True or False. Related concepts include elif (else if) for checking multiple conditions and else for catching all remaining cases.
Why it matters
- Data Validation: Ensures user input meets requirements before processing.
- Error Handling: Checks for edge cases like division by zero or empty lists.
- Game Logic: Determines win/loss states based on player scores or moves.
- Filtering: Selects specific items from a dataset that match criteria.
- State Management: Updates variables differently depending on current system status.
Syntax or steps
The basic structure requires three elements: the keyword if, a condition ending with a colon :, and an indented block of code. Python uses indentation (typically 4 spaces) to define scope, not curly braces.
if condition:
# Code to run if condition is True
You can extend this with elif and else clauses to handle mutually exclusive scenarios.
Example
Consider a simple temperature checker that categorizes weather conditions.
temperature = 15
if temperature > 30:
print("It is hot.")
elif temperature > 20:
print("It is warm.")
elif temperature > 10:
print("It is cool.")
else:
print("It is cold.")
Explanation:
temperature = 15: Initializes the variable.if temperature > 30:: Checks if it's hot. Since 15 is not greater than 30, this block is skipped.elif temperature > 20:: Checks if it's warm. Since 15 is not greater than 20, this block is skipped.elif temperature > 10:: Checks if it's cool. Since 15 is greater than 10, this condition isTrue.print("It is cool."): Executes because the previous condition was met.- The final
elseblock is ignored because a prior condition was satisfied.
Common mistakes
- Missing Colon: Forgetting the
:at the end of theifline causes aSyntaxError. - Inconsistent Indentation: Mixing tabs and spaces or failing to indent the body correctly leads to
IndentationError. - Assignment vs. Comparison: Using
=instead of==inside the condition assigns a value rather than comparing them, often resulting in unexpected behavior or errors. - Unreachable Code: Placing a broad condition (like
else) before specific ones prevents the specific checks from ever running.
When to use it
Use if statements for binary decisions or small sets of mutually exclusive branches. For complex routing based on many discrete values, consider alternatives.
| Scenario | Recommended Approach |
|---|---|
| Checking ranges (e.g., grades) | if / elif / else |
| Matching exact strings/integers | match-case (Python 3.10+) |
| Simple one-line assignment | Ternary operator (x if cond else y) |
Practice
Guided Exercise: Write a script that takes a number n and prints "Even" if divisible by 2, otherwise "Odd". Use the modulo operator %.
Challenge: Extend the exercise to check if the number is also positive. Print "Positive Even", "Negative Even", etc.
Hint: Combine conditions using and or nest if statements.
Quick check
Q: What happens if the condition in an if statement evaluates to False?
A: The indented block of code immediately following the if is skipped entirely, and execution continues with the next line after the block (or the next elif/else).
Summary
The if statement enables dynamic behavior by executing code based on runtime conditions. Mastering proper syntax, including colons and indentation, along with logical operators, is essential for writing robust and readable Python programs.