Drop #6 – If, Elif, Else – Python Decision Making
How do you teach a program to think?
You guide its decisions.
In Python, that means mastering the if, elif, and else statements, the foundation of logic flow.
Done right, conditionals make your code expressive and bulletproof. Done wrong, they turn it into spaghetti.
Let’s sharpen your control flow.
🧠 The Basic Structure
if condition_1:
do_something()
elif condition_2:
do_something_else()
else:
fallback()
Python reads top-down and executes the first true condition it finds. If none match, it falls to else.
🔍 Real-world example: Access Control
role = "admin"
if role == "admin":
print("Full access granted.")
elif role == "editor":
print("Edit permissions granted.")
elif role == "viewer":
print("Read-only access.")
else:
print("Access denied.")
Try changing the role and see how logic flows through the branches.
🚨 Common Pitfall: Overlapping Logic
Avoid writing conditions that can all be true, Python will stop at the first one:
score = 95
if score >= 90:
print("A")
elif score >= 80:
print("B")
This works, but if you accidentally put if score >= 80 first, you'll never hit "A".
Order matters.
✨ Best Practices
✅ Be explicit:
Use full comparisons like if user is not None instead of just if user.
✅ Keep blocks small:
A clean if block fits on a screen and reads top to bottom.
✅ Avoid deeply nested if trees:
Refactor with early returns or helper functions.
✅ Prefer match (Python 3.10+) for clean value matching:
match role:
case "admin":
print("Full access granted.")
case "editor":
print("Edit permissions granted.")
case "viewer":
print("Read-only access.")
case _:
print("Access denied.")
With match, you describe what to do, not how to check. It’s more readable and harder to mess up when handling multiple distinct values.
🔥 Mini Challenge
Rewrite this into a cleaner form:
if logged_in:
if is_admin:
print("Welcome, admin.")
else:
print("Welcome, user.")
else:
print("Please log in.")
How would you simplify it?
This was Drop #6 in the Python Drops series.
👉 Next up: for loops in Python — how to iterate cleanly, avoid off-by-one errors, and write more "Pythonic" loops.
Stay tuned. It’s going to get elegant.
SDET | QA Engineer | Test Automation Engineer | Playwright | Cypress | Robot Framework | Postman | Cucumber | Jenkins | Typescript | Javascript | Python | Manual Testing | Jira
3w💡 Great insight.
FullStack Software Engineer | React.js | Next.js | Typescript | Zustand | Radix | Material UI | Tailwind CSS | SCSS | Node.js | Django
3w💡 Great insight
QA | Quality Assurance Engineer | SDET | Cypress | Selenium | RestAssured | Appium | CTFL | API Testing | Automation Framework
3wGreat breakdown of Python conditionals! Clear examples and the addition of match from Python 3.10 make this drop a must-read for anyone solidifying their logic skills.
Software Engineer | Back-end | .Net | C# | React | Azure | SQL Server | Data Interoperability
3wGreat insights, thanks for sharing!