This guide explains if Statements: Make Decisions in Code through a focused example and practical reasoning. No prior knowledge of this specific operation is required.
Understanding the Concept
An if statement executes its indented block only if its condition is truthy. It is appropriate when an action should happen under one condition and can otherwise be skipped.
When You Would Use This
Display a low-battery warning only when the battery is below the threshold.
Step-by-Step Example
battery_percentage = 14
if battery_percentage < 20:
print("Charge your device")
print("Status check finished")
How the Example Works
The warning prints because 14 is below 20. The final message is outside the block and always prints.
Example Output
Charge your device
Status check finished
Try It Yourself
Change the percentage to exactly 20 and explain the result.
Common Beginner Mistakes
- Forgetting the colon after the condition.
- Placing a supposedly conditional statement outside the indentation.
- Using
=instead of==in a comparison.
Key Takeaways
- An
ifstatement executes its indented block only if its condition is truthy. - The warning prints because 14 is below 20.
- Avoid this mistake: Forgetting the colon after the condition.