Lesson explanation
After this lesson, you will be able to:
if, elif, and else for two-way and multi-way decisions.and, or, and not.A condition controls whether a block of code runs. Use if for the first rule, elif for additional rules, and else for the fallback when no earlier condition matches.
Python checks branches from top to bottom and stops at the first true branch. That makes branch order part of the logic. A broad rule placed too early can hide a more specific one below it.
Conditions can reuse the comparisons and logical operators you already know:
age >= 18
role == "admin" and is_active
is_vip or order_total >= 100
not is_suspendedEach branch line ends with a colon, and the code inside it is indented. This lesson uses that structure; the dedicated blocks lesson will examine indentation, nested blocks, and placeholders more closely.
💡 Tip: When two rules can both be true, place the more specific rule first.
Use if and else when exactly one of two outcomes should be selected.
maintenance_mode = False
if maintenance_mode:
print("Service unavailable")
else:
print("Service online")Output:
Service onlineOnly one branch runs.
Use elif when the same value can fall into one of several ordered categories.
battery_level = 42
if battery_level >= 80:
print("Battery: high")
elif battery_level >= 30:
print("Battery: medium")
else:
print("Battery: low")Output:
Battery: mediumThe first condition is false, so Python checks the next branch.
Logical operators let one branch depend on several facts.
role = "editor"
is_verified = True
if role == "editor" and is_verified:
print("Publishing enabled")
else:
print("Publishing blocked")Output:
Publishing enabledBoth sides of and must be true.
The first true branch wins, so rule order matters.
error_count = 12
if error_count >= 10:
print("Alert: critical")
elif error_count > 0:
print("Alert: warning")
else:
print("Alert: clear")Output:
Alert: criticalIf the warning rule came first, the critical case would never be reached.
else if; Python uses elif.if statements when only one result should be selected.else has no condition.Python for Developers
Assembled code
Generated code is hidden by default. Expand it only if you want to inspect what your current blank values produce.
0 / 6 tasks completed
| Decision | Python structure |
|---|
| Run code only when a rule matches | if condition: |
| Add another condition | elif condition: |
| Handle everything else | else: |
| Require both rules | and |
| Accept either rule | or |
| Reverse a boolean check | not |