Computer Programming 1 (Python) • Control Flow

If/Elif/Else Statements — I can write if/elif/else statements and design condition order to avoid logic bugs.

Master conditional branching to make your programs respond intelligently to any situation.

A Python coding terminal with a program flow and laptop.
Inside this lesson 10 sections 5 questions 8 figures

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

Ada Lovelace wrote the first algorithm for Charles Babbage's Analytical Engine. Her notes described how a machine could take different actions depending on intermediate results — the conceptual birth of conditional branching.

1946 • ENIAC & Branch Instructions

The ENIAC, one of the first electronic general-purpose computers, introduced hardware-level branch instructions. Engineers could physically wire the machine to skip ahead or loop back based on a comparison result.

1964 • BASIC's IF…THEN

The BASIC programming language brought conditional statements to beginners with a simple IF…THEN syntax. Millions of students typed their first decision-making code on early personal computers.

1991 • Python Is Released

Guido van Rossum released Python with a clean, readable 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.

1

Boolean Expressions

A Boolean expression is any expression that evaluates to True or False. Examples include score >= 90 and name == "Alice". These expressions are the "questions" your program asks.
2

Mutually Exclusive Branches

In an 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.
3

Top-Down Evaluation

Python checks conditions from top to bottom. The first True condition wins. This means the order of your conditions matters enormously — a careless order can create hard-to-find logic bugs.
4

The else Safety Net

The else clause is optional but powerful. It catches every case that none of your if or elif conditions anticipated. Think of it as the "everything else" category.
5

Indentation Is Syntax

In Python, indentation defines which lines belong inside a branch. If you forget to indent or indent inconsistently, Python will raise an IndentationError. Use four spaces per level.
✦

KEY TAKEAWAY

Think of an 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 Evaluation FlowStart: enter chainif conditionTrue or False?Truerun if blockFalseelif conditionTrue or False?Truerun elif blockFalserun else blockContinue program
This flowchart shows how Python evaluates an 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

if<condition1>:<block1>elif<condition2>:<block2>elif<condition3>:<block3>else:<defaultblock>if <condition_1>: <block_1> elif <condition_2>: <block_2> elif <condition_3>: <block_3> else: <default_block>

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)

ifscore>=60:grade="D"elifscore>=70:grade="C"elifscore>=80:grade="B"elifscore>=90:grade="A"else:grade="F"if score >= 60: grade = "D" elif score >= 70: grade = "C" elif score >= 80: grade = "B" elif score >= 90: grade = "A" else: grade = "F"

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

ifscore>=90:grade="A"elifscore>=80:grade="B"elifscore>=70:grade="C"elifscore>=60:grade="D"else:grade="F"if score >= 90: grade = "A" elif score >= 80: grade = "B" elif score >= 70: grade = "C" elif score >= 60: grade = "D" else: grade = "F"

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

When your conditions overlap (many values can satisfy more than one condition), always place the most specific or most restrictive condition first. Work from the narrowest match to the broadest. This prevents broader conditions from "stealing" values that should match a later, more specific branch.

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.

Three Common Conditional PatternsPattern ASimple ifif temp > 100: print("Hot!")Use when you onlyneed to act on ONEspecific situation.No action neededotherwise.1 branchPattern Bif / elseif age >= 18: print("Adult")else: print("Minor")Use when there areexactly TWO possibleoutcomes.2 branchesPattern Cif / elif / elseif score >= 90: grade = "A"elif score >= 80: grade = "B"elif score >= 70: grade = "C"else: grade = "F"Use when there areTHREE OR MOREpossible outcomes.3+ branchesChoose the simplest pattern that covers all your cases.
The three fundamental conditional patterns. Pattern A (simple if) handles one special case. Pattern B (if/else) handles binary choices. Pattern C (if/elif/else) handles multiple categories.

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.

FeatureMultiple if Statementsif/elif/else Chain
How many branches can run?All that are TrueExactly one
Conditions independent?Yes, each stands aloneNo, they are alternatives
PerformanceChecks every conditionStops at first True
Typical useUnrelated checksClassifying 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. 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 an if/elif/else chain.
  2. 2

    Step 2 — Plan the Condition Order

    We need to decide an order. One natural approach is youngest to oldest. With the elif structure, once we know age < 13 is False, we already know the age is 13 or more. So the next condition can simply check age < 18 instead of age >= 13 and age < 18. Each branch inherits the "already ruled out" knowledge from the branches above it.
    Order: child → teen → senior → adult (else)
  3. 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. 4

    Step 4 — Trace with a Test Value

    Suppose the customer enters age = 16. Python checks 16 < 13 → False. Then checks 16 < 18 → True. Python assigns price = 11 and skips the remaining branches.
    Output: Ticket price: $11
  5. 5

    Step 5 — Verify Edge Cases

    Always test boundary values. Age 13: first condition False, second condition 13 < 18 is True → $11 (correct, teen). Age 65: first two are False, 65 >= 65 is True → $9 (correct, senior). Age 18: first two are False, 18 >= 65 is 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.

PitfallWhat Goes WrongHow to Fix It
Broad condition firstA 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 elseAn 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 elifMultiple branches execute when only one should, producing confusing output or overwriting results.Use elif when the conditions are mutually exclusive alternatives.
Indentation errorsCode 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

When your conditionals produce unexpected results, add a temporary 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 LessonComing Next
if/elif/else for branchingmatch/case (Python 3.10+) for structural pattern matching — cleaner syntax when matching specific values
Checking one condition at a timeNested 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 valuesFunctions — 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

Explain in your own words why the order of conditions in an if/elif/else chain matters. Give a short real-world analogy (not from this lesson) to illustrate your point.
Show answer
The order matters because Python evaluates conditions from top to bottom and stops at the first True condition. If a broader condition appears before a narrower one, the broader condition will catch values that should have been handled by the narrower branch. A real-world analogy: imagine sorting mail into bins labeled "Letters from Mom," "Personal letters," and "All mail." If the "All mail" bin comes first, every piece goes in there and the more specific bins stay empty. You must check the most specific category first. This principle — most specific to most general — is the golden rule of condition ordering in any programming language.

Question 2: BASIC CALCULATION

Write a Python program that takes an integer variable 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
Here is the solution: 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

The following code has a logic bug. The programmer intends to classify a student's GPA (0.0–4.0) into Dean's List (3.5+), Honor Roll (3.0–3.49), Good Standing (2.0–2.99), or Academic Probation (below 2.0). Find the bug, explain what incorrect output it produces, and rewrite the corrected code. 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
The bug is that conditions are ordered from broadest to most restrictive. A GPA of 3.7 satisfies 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

A shipping company charges based on package weight: packages up to 1 lb cost $5.00, packages over 1 lb up to 5 lbs cost $10.00, packages over 5 lbs up to 20 lbs cost $20.00, and packages over 20 lbs cost $20.00 plus $1.50 for each pound over 20. Write a complete Python program that takes 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

A classmate writes two different programs to determine whether a number is positive, negative, or zero. Version A uses an 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
While both versions produce the same output for this simple case, they differ in important ways. First, efficiency: the if/elif/else chain stops evaluating as soon as one condition is True, so for a positive number it checks only one condition. Three separate if statements always check all three conditions, doing unnecessary work. Second, maintainability: the if/elif/else chain clearly communicates that the three cases are mutually exclusive alternatives. A future programmer reading Version B might not realize the conditions are supposed to be exclusive and might accidentally add overlapping logic. Third, safety under modification: if someone later changes Version B so that each branch assigns a value to a variable (instead of printing), the last True branch would silently overwrite the earlier assignment. In Version A, this can never happen because only one branch executes. The lesson is clear: when conditions represent mutually exclusive categories, always use if/elif/else to make the intent explicit and prevent future bugs.

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.

Varsity Tutors • Computer Programming 1 (Python) • If/Elif/Else Statements