SECTION 1
Historical Context & Motivation
Every program you have written so far likely runs straight from top to bottom — every line executes in order, every time. That works fine for simple scripts, but real-world software needs to make decisions. Should the game character jump or duck? Should the ATM dispense cash or show an error? The ability to branch — to choose which code runs based on current conditions — is one of the oldest and most fundamental ideas in computing.
1843 • Ada Lovelace's Notes
1946 • ENIAC & Branch Instructions
1964 • BASIC's IF…THEN
IF…THEN syntax. Millions of students typed their first decision-making code on early personal computers.1991 • Python Is Released
if/elif/else syntax. Unlike other languages that use curly braces, Python uses indentation, making the logical structure of conditions visually obvious.The central question that conditional statements answer is straightforward: How does a program choose what to do next? Without conditionals, a program is like a train locked on a single track. With if, elif, and else, your program becomes a network of tracks, switching directions based on signals you define.
SECTION 2
Core Principles & Definitions
Before you start writing conditional code, you need to understand a few foundational ideas. These principles apply not just to Python but to virtually every programming language that supports branching.
Boolean Expressions
True or False. Examples include score >= 90 and name == "Alice". These expressions are the "questions" your program asks.Mutually Exclusive Branches
if/elif/else chain, only one branch ever executes. Once Python finds a condition that is True, it runs that block and skips every remaining branch in the chain.Top-Down Evaluation
True condition wins. This means the order of your conditions matters enormously — a careless order can create hard-to-find logic bugs.The else Safety Net
if or elif conditions anticipated. Think of it as the "everything else" category.Indentation Is Syntax
IndentationError. Use four spaces per level.KEY TAKEAWAY
if/elif/else chain like a security checkpoint with multiple lanes. A guard checks your ID against the first rule. If you match, you go through that lane and skip the rest. If not, the next guard checks. The else is the final lane that says "everyone else goes here." The order of guards matters — if the first guard lets everyone through, nobody ever reaches the other lanes.SECTION 3
Visual Explanation — How Python Evaluates Conditions
if/elif/else chain. Diamonds represent condition checks. A True result sends execution to the right into the matching block. A False result drops execution down to the next condition. After any block runs, the program skips ahead to continue after the chain.Notice in the diagram that every path eventually reaches the same endpoint labeled "Continue program." This is the key visual insight: no matter which branch executes, exactly one branch runs, and then the program moves on. If none of the if or elif conditions are True and there is no else clause, then nothing inside the chain runs and the program simply continues. You can add as many elif branches as you need — just imagine more diamonds stacked downward in the diagram.
SECTION 4
How It Works — Syntax and Condition Order
The Basic Syntax Pattern
Every if/elif/else structure in Python follows the same pattern. You begin with if followed by a Boolean expression and a colon. The indented lines below it form the body of that branch. You can then add zero or more elif clauses (short for "else if") and optionally finish with else.
GENERAL SYNTAX
Each <condition> is a Boolean expression. Each <block> is one or more indented statements. Python evaluates conditions in order; the first True condition wins.
Why Condition Order Matters
Consider a grading program where you want to assign letter grades. Suppose you write the conditions in the wrong order, checking the broadest condition first:
BUGGY ORDER (DO NOT USE)
A student with a score of 95 matches score >= 60 on the very first check, so they receive a "D" — clearly wrong! The remaining elif branches are never reached.
CORRECT ORDER
By checking the most restrictive condition first (≥ 90), a student with a 95 correctly receives an "A". Each subsequent elif only catches the values that "fell through" the previous checks.
Golden Rule of Condition Order
SECTION 5
Detailed Breakdown — Common Conditional Patterns
Not every situation calls for the same conditional structure. Understanding the most common patterns helps you pick the right tool for the job. The diagram below classifies the three main patterns you will encounter and shows when each is appropriate.
Multiple Independent if Statements vs. an if/elif Chain
A very common mistake is using multiple standalone if statements when you actually need an if/elif chain. If you write three separate if statements, Python treats each one as an independent check — all three can fire. In an if/elif chain, only the first matching branch runs. Use separate if statements only when the conditions are truly independent — for example, checking both whether a user is logged in and whether the store is open, since those are unrelated facts.
| Feature | Multiple if Statements | if/elif/else Chain |
|---|---|---|
| How many branches can run? | All that are True | Exactly one |
| Conditions independent? | Yes, each stands alone | No, they are alternatives |
| Performance | Checks every condition | Stops at first True |
| Typical use | Unrelated checks | Classifying into categories |
Comparing multiple if statements with an if/elif/else chain
SECTION 6
Worked Example — Building a Ticket Pricing Program
Let's walk through a real scenario step by step. A movie theater charges different prices based on a customer's age: children (under 13) pay $8, teens (13–17) pay $11, adults (18–64) pay $14, and seniors (65 and older) pay $9. We need to write a program that asks for the customer's age and prints the correct ticket price.
Movie Ticket Pricing
- 1
Step 1 — Identify the Input and Categories
The input is the customer's age (an integer). We have four categories: child (age < 13), teen (13 ≤ age ≤ 17), adult (18 ≤ age ≤ 64), and senior (age ≥ 65). These categories are mutually exclusive — a person can belong to exactly one. That tells us we need anif/elif/elsechain. - 2
Step 2 — Plan the Condition Order
We need to decide an order. One natural approach is youngest to oldest. With theelifstructure, once we knowage < 13is False, we already know the age is 13 or more. So the next condition can simply checkage < 18instead ofage >= 13 and age < 18. Each branch inherits the "already ruled out" knowledge from the branches above it.Order: child → teen → senior → adult (else) - 3
Step 3 — Write the Code
Here is the complete program:age = int(input("Enter customer age: ")) if age < 13: price = 8 elif age < 18: price = 11 elif age >= 65: price = 9 else: price = 14 print("Ticket price: $" + str(price)) - 4
Step 4 — Trace with a Test Value
Suppose the customer enters age = 16. Python checks16 < 13→ False. Then checks16 < 18→ True. Python assignsprice = 11and skips the remaining branches.Output:Ticket price: $11 - 5
Step 5 — Verify Edge Cases
Always test boundary values. Age 13: first condition False, second condition13 < 18is True → $11 (correct, teen). Age 65: first two are False,65 >= 65is True → $9 (correct, senior). Age 18: first two are False,18 >= 65is False → else → $14 (correct, adult). The logic is sound.All boundary values produce correct prices ✓
SECTION 7
Common Pitfalls & How to Avoid Them
Even experienced programmers make mistakes with conditionals. Learning to recognize these pitfalls early will save you hours of debugging. The table below catalogs the most frequent errors and their fixes.
| Pitfall | What Goes Wrong | How to Fix It |
|---|---|---|
| Broad condition first | A general condition matches before a specific one, so the specific branch never runs. | Reorder from most restrictive to least restrictive. |
| Using = instead of == | Python raises a SyntaxError because = is assignment, not comparison. | Always use == for equality checks. |
| Missing the else | An unexpected value falls through all conditions, and a variable never gets assigned, causing a NameError later. | Include an else to handle unexpected inputs, even if just to print a message. |
| Separate if instead of elif | Multiple branches execute when only one should, producing confusing output or overwriting results. | Use elif when the conditions are mutually exclusive alternatives. |
| Indentation errors | Code that should be inside a branch is outside it (or vice versa), causing incorrect behavior without a clear error. | Always indent 4 spaces per level. Use a code editor that highlights indentation. |
Common conditional pitfalls and their solutions
DEBUGGING TIP
print() at the start of each branch — something like print("Entered branch A"). Run your program with several test values. If the wrong branch lights up, you know exactly where the logic is broken. This technique is called print debugging and it is one of the simplest yet most powerful tools in a programmer's toolkit.SECTION 8
Connection to Advanced Concepts
The if/elif/else chain is your introduction to control flow, but it is just the beginning. As you advance in programming, you will encounter more powerful decision-making structures. Understanding how today's concepts relate to what's ahead will help you see the bigger picture.
| This Lesson | Coming Next |
|---|---|
if/elif/else for branching | match/case (Python 3.10+) for structural pattern matching — cleaner syntax when matching specific values |
| Checking one condition at a time | Nested conditionals — placing an if inside another if for multi-layered decisions |
| Single decisions (run once) | Loops with conditionals — using if inside for or while loops to filter or process data repeatedly |
Comparisons like >= and == | Boolean logic — combining conditions with and, or, and not for complex decision-making |
| Hardcoded condition values | Functions — wrapping conditional logic inside reusable functions so the same decision-making code can be called from multiple places |
How if/elif/else connects to future topics
Every advanced structure listed above builds directly on what you learned today. If you can write a clean, well-ordered if/elif/else chain, you already have the mental framework for understanding nested conditionals, loop filtering, and even the Boolean algebra that underlies all digital circuits. Mastering condition order now prevents a whole category of bugs from following you into more complex projects.
SECTION 9
Practice Problems
Question 1: CONCEPTUAL
if/elif/else chain matters. Give a short real-world analogy (not from this lesson) to illustrate your point.Show answer
Question 2: BASIC CALCULATION
temperature and prints "Freezing" if the temperature is below 32, "Cold" if it is 32–59, "Warm" if it is 60–84, and "Hot" if it is 85 or above. Use proper if/elif/else syntax.Show answer
temperature = int(input("Enter temperature: "))
if temperature < 32:
print("Freezing")
elif temperature < 60:
print("Cold")
elif temperature < 85:
print("Warm")
else:
print("Hot")
Notice that we check from the lowest range upward. Once we know the temperature is not below 32 (because the first condition was False), we only need to check if it is below 60 for the "Cold" range. The elif structure carries forward the knowledge from previous failed checks, so we do not need compound conditions like temperature >= 32 and temperature < 60.Question 3: INTERMEDIATE
gpa = 3.7
if gpa >= 2.0:
status = "Good Standing"
elif gpa >= 3.0:
status = "Honor Roll"
elif gpa >= 3.5:
status = "Dean's List"
else:
status = "Academic Probation"
print(status)Show answer
gpa >= 2.0 on the very first check, so status is set to "Good Standing" even though 3.7 should be Dean's List. The elif branches for Honor Roll and Dean's List are never reached by any high-GPA student. The fix is to reverse the order, checking the most restrictive condition first:
gpa = 3.7
if gpa >= 3.5:
status = "Dean's List"
elif gpa >= 3.0:
status = "Honor Roll"
elif gpa >= 2.0:
status = "Good Standing"
else:
status = "Academic Probation"
print(status)
Now a GPA of 3.7 correctly triggers the first branch ("Dean's List"), and lower GPAs fall through to the appropriate categories.Question 4: APPLIED
weight as a float input and prints the shipping cost formatted to two decimal places. Include an else or initial check for invalid (non-positive) weights.Show answer
weight = float(input("Enter package weight in lbs: "))
if weight <= 0:
print("Invalid weight. Must be positive.")
elif weight <= 1:
cost = 5.00
elif weight <= 5:
cost = 10.00
elif weight <= 20:
cost = 20.00
else:
cost = 20.00 + 1.50 * (weight - 20)
if weight > 0:
print(f"Shipping cost: ${cost:.2f}")
This solution checks invalid weight first, which is a good defensive programming practice. The remaining conditions go from lightest to heaviest. For a 25-lb package, the first three elif conditions are all False, so the else block calculates 20.00 + 1.50 × (25 − 20) = 20.00 + 7.50 = $27.50. The f"...{cost:.2f}" formatting ensures the output always shows two decimal places.Question 5: CRITICAL THINKING
if/elif/else chain. Version B uses three separate if statements. Both produce the same output for any input. Are the two versions truly equivalent? Discuss at least two important differences beyond just the output, including efficiency, maintainability, and potential for future bugs if the code is later modified.Show answer
SUMMARY
Lesson Summary
Summary
In this lesson you learned how to use Python's if/elif/else statements to make your programs branch based on Boolean expressions. You saw that Python evaluates conditions from top to bottom and that only the first True branch executes in a chain. The else clause acts as a safety net for any case not covered by your conditions. You explored three common patterns: a simple if for single checks, if/else for binary decisions, and if/elif/else for multi-category classification.
The most critical skill from this lesson is designing condition order: always check the most restrictive condition first so that broader conditions don't steal matches from narrower ones. You also learned to distinguish between multiple independent if statements (where all True branches run) and an if/elif chain (where only one branch runs). With these tools, your programs can now respond intelligently to any input, setting the stage for loops, functions, and more advanced control flow.