Tutorials Python Python if elif else
Ch 14 / 58
Python Beginner 9 min read Chapter 14 of 58

Python if / elif / else

Decision-making is the soul of every program. Python's if, elif, and else statements control which blocks of code run based on conditions. This chapter covers the complete conditional toolkit — from basic if syntax to nested conditions, the elegant ternary operator, and Python 3.10's powerful match/case — with real-world examples throughout.

What you'll learn in this chapter
if statement syntax and indentation rules
if / else — two-branch decision making
if / elif / else — multiple conditions
Nested if statements and best practices
Ternary (conditional) expressions
match / case — Python 3.10+ pattern matching
Advertisement

What Are Conditional Statements?

Conditional statements allow your program to make decisions — executing different code depending on whether a condition is True or False. Without conditionals, every program would execute the same instructions every time, with no ability to react to input, data, or state.

Python uses indentation (whitespace) to define code blocks — not curly braces like Java or C. A consistent 4-space indent is the universal Python standard (PEP 8). Getting indentation wrong causes an IndentationError.

Python indentation rule All statements in the same block must have identical indentation. The standard is 4 spaces (not a tab). Mixing spaces and tabs causes a TabError. Most editors auto-configure this when you save a .py file.
if
Run if condition is True
else
Run when if is False
elif
Extra conditions to check
Indentation
4 spaces define the block

The if Statement

The if statement is the simplest conditional. It evaluates a condition — any expression that can be truthy or falsy — and executes the indented block only if the condition is True. If the condition is False, the block is skipped entirely.

Python — if_statement.py
# Syntax: if condition:
#             body  (indented 4 spaces)

age = 20

if age >= 18:
    print("You are an adult.")   # runs — 20 >= 18 is True

# Condition is False — block is skipped
score = 45
if score >= 50:
    print("Passed!")             # skipped — 45 >= 50 is False

print("Program continues...")  # always runs (outside the block)

# Any truthy value triggers the block
name = "Alice"
if name:                       # non-empty string is truthy
    print(f"Hello, {name}!")   # Hello, Alice!

items = []
if items:                      # empty list is falsy — block skipped
    print("Has items")

# Multiple statements in the block
temp = 38.5
if temp > 37.5:
    print("Fever detected!")
    print("Please rest and hydrate.")
    print(f"Temperature: {temp}°C")
if condition:
The colon : at the end is mandatory. Forgetting it causes SyntaxError: expected ':'.
4-space indent
Every line in the if block must be indented by the same amount. PEP 8 mandates 4 spaces — never mix tabs and spaces.
if name:
Any value works as a condition — Python calls bool() on it. Non-empty strings, non-zero numbers, and non-empty collections are truthy.

if / else — Two-Branch Decisions

Adding an else clause gives your program a fallback — code that runs only when the if condition is False. Exactly one branch always executes: either the if block or the else block, never both, never neither.

Python — if_else.py
# Basic if / else
age = 16

if age >= 18:
    print("Adult — can vote")
else:
    print("Minor — cannot vote")  # this runs

# Number classification
number = -7
if number >= 0:
    print(f"{number} is non-negative")
else:
    print(f"{number} is negative")   # -7 is negative

# Even or odd
n = 13
if n % 2 == 0:
    print(f"{n} is even")
else:
    print(f"{n} is odd")            # 13 is odd

# Login check
password = input("Enter password: ")  # simulated
CORRECT  = "secret123"
if password == CORRECT:
    print("Access granted ✅")
else:
    print("Wrong password ❌")

# if/else as an expression (ternary style)
status = "pass" if n >= 50 else "fail"
print(status)                         # fail (13 < 50)
else has no condition The else clause never takes a condition — writing else x > 0: is a SyntaxError. It simply runs when every preceding condition was False.
Advertisement
🐍
K2infocom Python Masterclass & Backend Development
Master Python, Django & Backend APIs with AI
Go from absolute beginner to building production-ready REST APIs, web applications, and ML pipelines. Real projects, live mentoring in Vadodara, and placement support included.
2,400+
Students Enrolled
4.9 ⭐
Google Rating
6 Months
Full Program
100%
Placement Support
Python 3 Django & DRF FastAPI PostgreSQL Machine Learning Docker & AWS Real Projects AI Tools

if / elif / else — Multiple Conditions

elif (short for "else if") lets you test multiple conditions in sequence. Python checks each condition top-to-bottom and runs the first matching block only. Once a match is found, all remaining elif and else branches are skipped. You can have any number of elif clauses.

Python — if_elif_else.py
# Grade classifier
score = 72

if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"         # ← this runs: 72 >= 70
elif score >= 60:
    grade = "D"
else:
    grade = "F"
print(f"Score: {score} → Grade: {grade}")
# Score: 72 → Grade: C

# Season detector
month = 7
if month in [12, 1, 2]:
    season = "Winter"
elif month in [3, 4, 5]:
    season = "Spring"
elif month in [6, 7, 8]:
    season = "Summer"    # ← July = 7
else:
    season = "Autumn"
print(season)              # Summer

# BMI classifier
bmi = 27.4
if bmi < 18.5:
    print("Underweight")
elif bmi < 25:
    print("Normal weight")
elif bmi < 30:
    print("Overweight")         # ← 27.4 < 30
else:
    print("Obese")
Clause Has condition? How many? When it runs
if
Yes
Exactly 1 (required) When its condition is True
elif
Yes
0 or more When all above conditions are False and this one is True
else
No
0 or 1 (optional) When all preceding conditions are False

Nested if Statements

Nested if means placing an if statement inside another if block. Each level of nesting adds 4 more spaces of indentation. While nesting is sometimes necessary, deep nesting (3+ levels) is a code smell — prefer early returns, logical operators, or elif to flatten the structure.

Python — nested_if.py
# Nested if — loan eligibility
age    = 28
income = 55000
credit = 720

if age >= 21:
    if income >= 30000:
        if credit >= 700:
            print("Loan approved ✅")
        else:
            print("Improve credit score")
    else:
        print("Income too low")
else:
    print("Must be 21 or older")
# Loan approved ✅

# ✅ Better: flattened with 'and' — same logic, cleaner
if age >= 21 and income >= 30000 and credit >= 700:
    print("Loan approved ✅")
elif age < 21:
    print("Must be 21 or older")
elif income < 30000:
    print("Income too low")
else:
    print("Improve credit score")

# Early return pattern (inside a function) avoids deep nesting
def process_order(user, cart, payment):
    if not user:
        return "Please log in"       # guard clause
    if not cart:
        return "Cart is empty"
    if not payment:
        return "No payment method"
    return "Order placed! ✅"        # happy path last
Avoid deep nesting Code nested 3+ levels deep is hard to read and test. The guard clause pattern (early return on failure conditions) and combining conditions with and/or keep code flat and readable.

Ternary (Conditional) Expression

Python's ternary expression (also called a conditional expression) condenses a simple if/else into a single readable line. The syntax is value_if_true if condition else value_if_false. It's an expression (not a statement) — it returns a value and can be used anywhere a value is expected.

Python — ternary_operator.py
# Syntax: result = value_if_true if condition else value_if_false

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

# Equivalent multi-line version:
if age >= 18:
    status = "adult"
else:
    status = "minor"

# In expressions and function calls
n = -7
print(f"{n} is {'negative' if n < 0 else 'positive'}")
# -7 is negative

print(abs(n) if n < 0 else n)     # 7

# In a list comprehension
nums = [-3, 1, -5, 7, -2]
labels = ["pos" if x > 0 else "neg" for x in nums]
print(labels)
# ['neg', 'pos', 'neg', 'pos', 'neg']

# Chained ternary (avoid for readability!)
score = 78
grade = "A" if score >= 90 else "B" if score >= 80 else "C"
print(grade)           # C

# As a default value
username = ""
display = username if username else "Anonymous"
print(display)         # Anonymous
When to use the ternary expression Use it for simple, single-value assignments where both branches are short. If either branch needs multiple statements, or if the condition is complex, use a regular if/else block — readability always wins.

match / case — Pattern Matching (Python 3.10+)

Python 3.10 introduced the match statement — a powerful pattern-matching construct that goes far beyond a simple switch/case. It can match literal values, destructure collections, match object attributes, and use guard conditions. The _ pattern is the wildcard (equivalent to default).

Python — match_case.py (Python 3.10+)
# Basic literal matching
command = "quit"

match command:
    case "start":
        print("Starting...")
    case "stop":
        print("Stopping...")
    case "quit":
        print("Quitting!")     # ← this runs
    case _:                  # wildcard — matches anything
        print("Unknown command")

# Match with OR patterns (Python 3.10+)
status = 404
match status:
    case 200 | 201 | 204:
        print("Success")
    case 400:
        print("Bad Request")
    case 401 | 403:
        print("Auth error")
    case 404:
        print("Not Found")        # ← this runs
    case _:
        print("Other error")

# Match with guard conditions
point = (3, 7)
match point:
    case (0, 0):
        print("Origin")
    case (x, 0):
        print(f"On x-axis at {x}")
    case (0, y):
        print(f"On y-axis at {y}")
    case (x, y) if x == y:
        print(f"Diagonal at {x}")
    case (x, y):
        print(f"Point at ({x}, {y})")  # ← matches (3, 7)
Python version required match/case requires Python 3.10 or later. Check your version with python --version. For older versions, use if/elif/else chains or a dictionary dispatch pattern instead.

Practice Python Online — Free Compilers

Don't want to install anything yet? Practice all if/elif/else examples from this chapter directly in your browser with these free Python environments.

▶
Online Python 3 Compiler
Write, run and debug Python code in your browser. No installation required. Test every conditional statement example instantly.
Open Compiler
Replit
Full IDE online
Google Colab
Free GPU notebooks
JupyterLite
Notebooks in browser
Programiz
Beginner-friendly
Chapter Summary
  • if executes a block only when its condition is truthy. The colon (:) and 4-space indentation are mandatory.
  • else runs when the if (and all preceding elif) conditions are False. It never has its own condition.
  • elif (else if) checks additional conditions in sequence. Python executes the first matching block only and skips all subsequent ones.
  • You can have any number of elif clauses, but at most one else (and it must come last).
  • Nested if statements work but should be avoided beyond 2 levels. Use and/or to flatten conditions, or early-return guard clauses inside functions.
  • Ternary expression: x if condition else y — a single-line conditional that returns a value. Best for simple assignments.
  • match/case (Python 3.10+) offers structural pattern matching — literal values, OR patterns (|), destructuring tuples, and guard conditions (case x if x > 0).
  • Any expression is a valid condition — Python calls bool() on it. Empty collections, 0, "", and None are all falsy.
⚡
Free Resource
Download our Python if / elif / else Cheat Sheet
if syntax, elif chains, ternary expression, nested if tips & match/case — one printable page.
Get Sheet
Advertisement
Quick Check — Test Your Understanding
Question & Answer
✓ Answer

Using elif means the conditions are mutually exclusive — only the first matching branch runs, and all others are skipped. Once a match is found, the entire if/elif/else chain is exited.

Using a second if creates a completely independent check — both conditions are evaluated regardless of the first result. This means both blocks could run if both conditions are true.

x = 15
# With elif — only one branch runs:
if x > 10: print(">10")   # runs
elif x > 5: print(">5")  # skipped (first matched)

# Two ifs — both run:
if x > 10: print(">10")   # runs
if x > 5:  print(">5")   # also runs!
✓ Answer

The ternary (conditional) expression syntax in Python is: value_if_true if condition else value_if_false. It is an expression — it evaluates to a value and can be assigned to a variable, used in function arguments, f-strings, or list comprehensions.

label = "pass" if score >= 50 else "fail"

Use it when both branches are short single values and the condition is simple. Avoid chaining multiple ternary operators — the result becomes hard to read. Use a regular if/else block instead when logic grows complex.

✓ Answer

Python uses indentation (whitespace) to define code blocks as a design choice for readability. Guido van Rossum's goal was code that reads like pseudocode — indentation is already used visually in every language, so Python makes it syntactically significant, eliminating the need for braces entirely.

  • IndentationError — inconsistent indentation (e.g. mixing 2 and 4 spaces in the same block)
  • TabError — mixing tabs and spaces (use spaces only per PEP 8)
  • SyntaxError — missing indent after if:, else:, or elif:
  • Logic errors — wrong indentation level puts code inside or outside the block unintentionally
✓ Answer

The guard clause (or early return) pattern places all failure/edge-case checks at the top of a function with immediate return statements, keeping the happy path at the lowest indentation level with no nesting.

# ❌ Deep nesting — hard to follow
def process(user, data):
    if user:
        if data:
            return handle(user, data)

# ✅ Guard clauses — clean and flat
def process(user, data):
    if not user: return "No user"
    if not data: return "No data"
    return handle(user, data)  # happy path
✓ Answer

match/case (Python 3.10+) is structural pattern matching — far more powerful than a simple switch/case or if/elif chain. Key differences:

  • Pattern destructuring: case (x, y): binds x and y from a tuple automatically — no manual indexing.
  • OR patterns: case 400 | 404 | 500: matches any of the listed values in one case.
  • Guard conditions: case x if x > 0: adds extra conditions to a pattern.
  • Wildcard: case _: matches anything — the equivalent of else.
  • if/elif is universal (works in any Python 3 version) and is preferred for simple boolean conditions. Use match when matching against the structure of data.
MCQ 1 of 3
What does "pass" if 5 > 3 else "fail" evaluate to?
MCQ 2 of 3
How many elif clauses can a single if statement have?
MCQ 3 of 3
What is printed by: x = 15; print("A" if x > 20 else "B" if x > 10 else "C")?

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel