Python Tutorial 0/52 lessons ~6 min read Lesson 9
Conditionals (if / elif / else)
Python conditionals use if, elif, else with colons and indented blocks.
Course progress0%
Focus
9 guided sections
Practice signal
Examples included
Career prep
Interview Q&A included
Introduction
Python conditionals use if, elif, else with colons and indented blocks. Python 3.10+ adds match-case for structural pattern matching.
Understanding the topic
Core concepts to understand:
elifchains avoid nested ifs.- Ternary:
x if cond else y. - Truthy/falsy: empty collections, 0, None, '' are falsy.
- match-case (3.10+) for pattern matching.
Syntax reference
Visual flow / code:
python
score = 85if score >= 90:grade = "A"elif score >= 80:grade = "B"else:grade = "C"# Ternarystatus = "pass" if score >= 60 else "fail"# match-case (3.10+)match status:case "pass": print("🎉")case "fail": print("😢")case _: print("?")
Execution workflow
1Conditionals (if / elif / else) Workflow
1 / 4elif chains avoid nested ifs
elif chains avoid nested ifs.
Real-world use
Pattern matching with match is now standard in modern Python codebases — especially for handling API responses, state machines, and parsing.
Best practices
- Use
elifover nested ifs. - Exploit truthy/falsy for cleaner checks.
- Prefer match-case for multi-branch dispatch.
Common mistakes
if x == True:is redundant — justif x:.
Advanced interview questions
Interview Prep
Practice concise answers, then expand each card for the explanation.
1BeginnerQuestionWhat's truthy/falsy?+
Answer
Every object has a truth value used in
if and while. Falsy values include None, False, zero of any numeric type, and empty containers like '', [], {}, set(). Everything else is truthy by default, unless a class defines __bool__ or __len__ to say otherwise.Follow-up
How does a custom class control its truthiness?
2IntermediateQuestionWhat's match-case?+
Answer
match/case, added in Python 3.10, is structural pattern matching. It compares a subject against patterns that can destructure sequences, mappings, and class instances, bind variables, and have guards with if. It is more than a switch statement, and a bare name in a pattern captures a value rather than comparing against a variable.Follow-up
Why does case x match anything rather than compare to variable x?
3BeginnerQuestionHow does ternary work?+
Answer
Python's conditional expression is written
value_if_true if condition else value_if_false. The condition is evaluated first and only the chosen branch is evaluated. It is best for short, simple choices; nested ternaries quickly become hard to read.Summary
In summary: elif chains > nested ifs. match-case for modern dispatch.
Ready to mark this lesson complete?Track your journey across the entire course.