Python

Python Fundamentals

Conditional Statements

Python uses indentation (not {}) to define code blocks — this is enforced, not just a style choice.

JrCodex·5 min read

Jr Codex Python Notes

Level: Beginner Prerequisites: Chapter 9 Time to complete: ~20 minutes


Table of Contents

  1. The if Statement
  2. if / elif / else
  3. Nested Conditionals
  4. Truthy & Falsy Values Revisited
  5. The Ternary (Conditional) Expression
  6. match-case (Python 3.10+)
  7. Summary & Next Steps

1. The if Statement

Python uses indentation (not {}) to define code blocks — this is enforced, not just a style choice.

age = 20
 
if age >= 18:
    print("You are an adult.")
Indentation IS the syntax
─────────────────────────────────────
  if age >= 18:
  ····print("You are an adult.")   ← 4 spaces (standard), consistently applied
─────────────────────────────────────

Mixing tabs and spaces, or inconsistent indentation, raises an IndentationError. Stick to 4 spaces (PEP 8 standard) — most editors do this automatically.


2. if / elif / else

score = 75
 
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
else:
    grade = "F"
 
print(grade)      # "C"

Only the first matching branch runs — Python doesn't check later elifs once one condition is true.

Evaluation Flow
─────────────────────────────────────
  score = 75
  score >= 90?  → False, skip
  score >= 80?  → False, skip
  score >= 70?  → True  → grade = "C", STOP (skip else)
─────────────────────────────────────

3. Nested Conditionals

Conditionals can be nested inside each other, but deep nesting hurts readability — usually a sign to refactor into a function (Module 2) or flatten the logic.

age = 25
has_license = True
 
if age >= 18:
    if has_license:
        print("Can drive")
    else:
        print("Too young to have a license, or hasn't gotten one")
else:
    print("Not old enough to drive")
 
# Often better — flatten with `and`
if age >= 18 and has_license:
    print("Can drive")
else:
    print("Cannot drive")

4. Truthy & Falsy Values Revisited

Chapter 2 introduced truthiness via bool(). Conditionals are where it actually gets used — you rarely need == True or == False:

items = []
 
# Verbose / non-Pythonic
if len(items) == 0:
    print("Empty")
 
# Idiomatic — empty list is falsy
if not items:
    print("Empty")
 
name = ""
if name:                 # False for empty string
    print(f"Hello, {name}")
else:
    print("No name provided")
Instead of...Write...
if x == True:if x:
if x == False:if not x:
if len(my_list) == 0:if not my_list:
if my_var == None:if my_var is None:

5. The Ternary (Conditional) Expression

A one-line if/else for simple value assignment:

age = 20
status = "adult" if age >= 18 else "minor"
print(status)     # "adult"
 
# Equivalent to:
if age >= 18:
    status = "adult"
else:
    status = "minor"

Use it for simple value choices; avoid it for complex logic — nesting ternaries hurts readability fast:

# Avoid — hard to read
grade = "A" if score >= 90 else "B" if score >= 80 else "C" if score >= 70 else "F"
 
# Prefer if/elif/else for anything beyond one condition

6. match-case (Python 3.10+)

Python's version of a switch statement — pattern matching against a value:

def http_status_message(code):
    match code:
        case 200:
            return "OK"
        case 404:
            return "Not Found"
        case 500:
            return "Server Error"
        case _:                    # `_` is the wildcard — like `else`
            return "Unknown Status"
 
print(http_status_message(404))    # "Not Found"
print(http_status_message(999))     # "Unknown Status"

match supports more than simple values — it can match structure (useful once you're comfortable with tuples/lists):

def describe_point(point):
    match point:
        case (0, 0):
            return "Origin"
        case (0, y):
            return f"On the y-axis at {y}"
        case (x, 0):
            return f"On the x-axis at {x}"
        case (x, y):
            return f"Point at ({x}, {y})"
 
print(describe_point((0, 5)))     # "On the y-axis at 5"
print(describe_point((3, 4)))      # "Point at (3, 4)"

When to use match vs if/elif: match shines when checking one variable against many discrete values or shapes. For range checks (score >= 90) or combined conditions, if/elif is still the natural choice.


7. Summary & Next Steps

Key Takeaways

  • Python uses indentation to define blocks — be consistent (4 spaces is standard).
  • Only the first true branch in an if/elif/else chain executes.
  • Prefer truthy/falsy checks (if not items:) over explicit == True/== 0 comparisons.
  • The ternary expression (x if cond else y) is great for simple one-line choices; match-case is great for matching one value against many discrete cases.

Concept Check

  1. Why does Python raise an IndentationError and what usually causes it?
  2. Rewrite if len(name) == 0: in a more Pythonic way.
  3. When would match-case be a better fit than a chain of elifs?

Next Chapter

Chapter 11: Loops & Iteration Basics


Jr Codex — 1-on-1 Personalized Coaching | Back to Module Index