Python • Control Flow

If/Elif/Else Statements — Write if/elif/else statements with correct indentation

Teach your programs to make decisions by choosing different paths based on conditions.

Code braces with terminal and markup symbols representing Python programming.
Inside this lesson 10 sections 5 questions 8 figures

SECTION 1

Historical Context & Motivation

Every useful program needs the ability to make decisions. Without decision-making, a program could only execute the same instructions in the same order every single time it runs. Imagine a calculator that could add but could never check whether you accidentally divided by zero — it would crash constantly. The concept of conditional branching — telling a computer to do different things depending on circumstances — is one of the oldest and most essential ideas in all of computing.

1843 • Ada Lovelace's Notes

Ada Lovelace described how Charles Babbage's Analytical Engine could branch to different instruction cards based on intermediate results — the earliest written concept of conditional logic in computing.

1957 • FORTRAN's IF Statement

FORTRAN, one of the first high-level programming languages, introduced the arithmetic IF statement, allowing programs to jump to different line numbers based on whether a value was negative, zero, or positive.

1972 • C Language and Curly Braces

The C programming language popularized the if/else structure using curly braces { } to group code blocks. This syntax influenced dozens of later languages including Java, JavaScript, and C++.

1991 • Python's Indentation-Based Syntax

Guido van Rossum released Python, which replaced curly braces with mandatory indentation. This design choice made code structure visible and enforced readability as part of the language itself.

2000 • Python 2 and elif

Python's if/elif/else structure became a model of clean conditional syntax. The keyword 'elif' (a contraction of 'else if') reduced nesting and kept multi-branch decisions flat and readable.

The central question that conditional statements answer is straightforward: how can a program choose what to do next based on the current situation? Python's approach to this question is uniquely elegant. Instead of relying on special punctuation like braces or keywords like "end," Python uses indentation — the whitespace at the beginning of a line — to show which code belongs to which decision branch. This means that learning to write correct conditionals in Python is inseparable from learning to indent correctly.

SECTION 2

Core Principles & Definitions

Before writing your first conditional, you need to understand a handful of foundational ideas. Each of these principles works together to give Python its clean, readable approach to decision-making.

1

Boolean Conditions

Every if statement tests a condition that evaluates to either True or False. These Boolean values are the gatekeepers that decide which branch runs.
2

The Colon (:) Signals a Block

In Python, every if, elif, or else line must end with a colon. The colon tells Python, "a new indented block of code is about to begin."
3

Indentation Defines Scope

Python uses exactly 4 spaces (by convention) to define which lines belong to a conditional branch. If a line is indented under an if statement, it only runs when that condition is True.
4

Mutual Exclusion with elif/else

When you chain if → elif → else, Python checks each condition in order and runs only the first matching branch. The remaining branches are skipped entirely.
5

else Is the Catch-All

The else block has no condition — it runs when every preceding if and elif condition was False. It guarantees that at least one branch will always execute.
✦

KEY TAKEAWAY

Think of an if/elif/else chain like a multiple-choice tollbooth on a highway. Your car (the program) approaches several lanes, but each lane has a sign with a condition. You drive into the first lane whose sign matches your situation. The "else" lane has a sign that says "Everyone else" — if no other lane matched, you go there. You can only ever take one lane per trip.

SECTION 3

Visual Explanation — Flowchart of Conditional Logic

The following flowchart shows how Python evaluates an if/elif/else chain. Notice that once a condition evaluates to True, its block executes and the program jumps past all remaining branches. This top-down, first-match behavior is the key to understanding how conditional chains work.

How Python Evaluates if / elif / elseStart of chainif condition?Trueif blockFalse ↓elif condition?Trueelif blockFalse ↓else blockContinue program◆ Diamond = decision▭ Rectangle = action--- Dashed = rejoin path
The diamond shapes represent condition checks. When a condition is True, execution moves right into that block. When False, it falls down to the next check. All paths eventually rejoin at "Continue program."

Notice in the diagram that the three colored blocks — if block, elif block, and else block — are mutually exclusive. Only one of them will ever execute during a single pass through the chain. This is a crucial difference from writing three separate if statements, which would each be checked independently.

SECTION 4

How It Works — Syntax and Indentation Rules

Python's conditional syntax follows a strict pattern. Understanding this pattern is essential because even a small indentation error will cause your program to either crash with an IndentationError or, worse, produce incorrect results silently. Let's break down the exact structure.

The Basic if Statement

IF STATEMENT SYNTAX

if<condition>:<indentedblock>if <condition>: <indented block>

The <condition> is any expression that evaluates to True or False. The indented block (4 spaces) runs only when the condition is True.

The Full if/elif/else Chain

FULL CHAIN 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>

You can have zero or more elif branches. The else is optional but ensures a default action. Each keyword (if, elif, else) must be at the same indentation level.

Indentation Rules

  • ✓ Use 4 spaces per level. This is the standard convention defined in PEP 8, Python's official style guide. Most code editors insert 4 spaces when you press Tab.
  • ✓ Never mix tabs and spaces. Mixing them causes Python 3 to raise a TabError. Configure your editor to convert tabs to spaces.
  • ✓ All lines in a block must share the same indentation. If one line has 4 spaces and the next has 5, Python raises an IndentationError.
  • ✓ The if, elif, and else keywords must align vertically. They belong to the same chain only if they share the same indentation level.
⚠

Common Pitfall

Forgetting the colon at the end of an if, elif, or else line is the single most common syntax error for beginners. Python will raise a SyntaxError and point to the line. Always check for the colon before looking for other issues.

SECTION 5

Detailed Breakdown — Correct vs. Incorrect Indentation

Because indentation in Python isn't just about style — it's about correctness — let's examine exactly what proper and improper indentation looks like. The diagram below places correct code side-by-side with common errors so you can train your eye to spot problems.

Correct vs. Incorrect Indentation✓ CORRECTscore = 85if score >= 90:grade = "A"elif score >= 80:grade = "B"else:grade = "C or below"# 4 spaces = 1 indent level✗ INCORRECTscore = 85if score >= 90:grade = "A"← 2 spaces!elif score >= 80:grade = "B"← 3 spaces!else:grade = "C or below"← 0 spaces!IndentationError: unexpected indentIndentation Levels VisualizedLevel 0 — keywords (if, elif, else)Level 1 — code inside a branch (4 spaces)Level 2 — nested if inside a branch (8 spaces)if x > 0: ← Level 0 if x > 10: ← Level 1 print("Big!") ← Level 2
Left panel: correct indentation with consistent 4-space blocks. Right panel: inconsistent spacing (2, 3, and 0 spaces) that triggers an IndentationError. Bottom: how indentation levels stack when you nest conditionals.
Comparison OperatorsSymbolExampleResult
Equal to==5 == 5True
Not equal to!=5 != 3True
Greater than>7 > 3True
Less than<2 < 8True
Greater than or equal>=5 >= 5True
Less than or equal<=4 <= 3False

Comparison operators commonly used in if/elif conditions

SECTION 6

Worked Example — Grading Program

Let's build a program that takes a student's test score and assigns a letter grade. This is a classic use of an if/elif/else chain because the score falls into exactly one of several ranges.

Assigning a Letter Grade Based on a Test Score

  1. 1

    Step 1 — Identify the Problem

    We have a numeric score (0–100) and need to map it to a letter grade: A (90–100), B (80–89), C (70–79), D (60–69), or F (below 60). Each score belongs to exactly one category, so we need mutually exclusive branches.
  2. 2

    Step 2 — Write the if Statement (Check for A)

    We start with the highest range. The code begins with if score >= 90: followed by an indented line: grade = "A". Note the 4 spaces before grade and the colon after the condition.
    if score >= 90: grade = "A"
  3. 3

    Step 3 — Add elif Branches (B, C, D)

    Each elif checks the next range. Because Python stops at the first true condition, we don't need to write 80 <= score < 90. If we reach elif score >= 80, we already know the score is below 90 because the if didn't match.
    elif score >= 80: grade = "B" elif score >= 70: grade = "C" elif score >= 60: grade = "D"
  4. 4

    Step 4 — Add the else (F)

    If none of the above conditions matched, the score must be below 60. The else block catches all remaining cases.
    else: grade = "F"
  5. 5

    Step 5 — Complete Program and Test

    Putting it all together and testing with score = 85: Python checks 85 >= 90 → False, then 85 >= 80 → True. The program assigns grade = "B" and skips all remaining branches.
    Output: grade = "B"
💡

Pro Tip

When using elif chains with numeric ranges, start from the highest (or lowest) value and work in one direction. This lets you write simpler conditions since previous checks have already eliminated other ranges.

SECTION 7

Strengths, Limitations, and Common Mistakes

Python's if/elif/else structure is powerful and readable, but like any tool, it has strengths you should leverage and pitfalls you should watch for. Understanding when this structure shines — and when other approaches might be better — is a sign of growing programming maturity.

StrengthsLimitations
Highly readable — indentation makes the structure visually obviousLong elif chains (10+) can become hard to manage; dictionaries may be cleaner
Handles complex Boolean logic with and, or, notPython does not have a built-in switch/case until Python 3.10's match statement
Guaranteed mutual exclusion — only one branch executes per chainDeeply nested conditionals (if inside if inside if) hurt readability
Works with any data type that can be evaluated as truthy or falsyOrder of conditions matters — putting a broader condition first can accidentally shadow a more specific one

When if/elif/else shines and where to watch out

Common Mistakes to Avoid

MistakeWhat HappensFix
Using = instead of ==SyntaxError — assignment is not allowed in a conditionAlways use == for comparison
Forgetting the colonSyntaxError on the lineEvery if/elif/else line ends with :
Inconsistent indentationIndentationErrorUse exactly 4 spaces per level; configure your editor
Using multiple if instead of elifMultiple branches may execute when only one shouldUse elif for mutually exclusive conditions

The four most common beginner mistakes with conditionals

✦

KEY TAKEAWAY

Think of the difference between multiple if statements and an if/elif chain like the difference between multiple security guards who each independently check your ID versus a single checkpoint where you only need to pass once. With separate if statements, each one checks you regardless of the others. With elif, once you pass through one gate, you skip the rest.

SECTION 8

Connection to Advanced Control Flow

The if/elif/else statement is the foundation of all decision-making in Python, but as your programs grow more complex, you'll encounter more sophisticated control flow tools. Understanding how basic conditionals connect to these advanced features gives you a roadmap for your future learning.

Basic ConceptAdvanced VersionWhen to Use It
if/elif/elsematch/case (Python 3.10+)When you're matching a single value against many patterns (like a menu system)
Simple if/else assignmentTernary expression: x = "yes" if flag else "no"When you need a one-line conditional assignment
Long elif chains mapping valuesDictionary lookup: result = lookup[key]When every branch simply maps one value to another
Conditionals inside loopsList comprehensions with conditionsWhen filtering or transforming a collection in one concise line
Error checking with iftry/except exception handlingWhen handling unexpected errors rather than predictable conditions

From basic conditionals to advanced control flow patterns

Even as you learn these advanced tools, you'll find that the basic if/elif/else chain remains the workhorse of everyday Python programming. Mastering indentation and conditional logic now builds a strong foundation for every control flow concept you'll encounter in the future, including loops, functions, and class definitions — all of which use the same indentation rules.

SECTION 9

Practice Problems

Test your understanding with these five problems. They increase in difficulty, starting with a conceptual question and building up to a challenge that requires you to combine multiple ideas.

Question 1: CONCEPTUAL

What is the difference between using three separate if statements and using an if/elif/elif chain? Explain what happens when x = 15 and we have conditions x > 10, x > 5, and x > 0.
Show answer
With three separate if statements, Python evaluates every condition independently. Since 15 satisfies all three conditions (15 > 10, 15 > 5, 15 > 0), all three blocks will run. With an if/elif/elif chain, Python stops at the first true condition (x > 10) and skips the rest. Use elif when you want exactly one branch to execute.

Question 2: BASIC CALCULATION

Write a Python program that takes a variable temperature and prints "Hot" if it is 90 or above, "Warm" if it is 70–89, "Cool" if it is 50–69, and "Cold" if it is below 50. Use proper indentation.
Show answer
The correct code is: if temperature >= 90: / print("Hot") / elif temperature >= 70: / print("Warm") / elif temperature >= 50: / print("Cool") / else: / print("Cold"). By starting with the highest threshold and working down, each elif only needs a single comparison. The else catches anything below 50.

Question 3: INTERMEDIATE

A movie ticket costs $12 for adults (18+), $8 for teens (13–17), and $5 for children (under 13). Seniors (65+) get a $3 discount off the adult price. Write an if/elif/else chain that sets a variable ticket_price based on age. Be careful about the order of conditions.
Show answer
The key insight is that seniors are also adults (65 is ≥ 18), so you must check for seniors before the general adult condition: if age >= 65: / ticket_price = 9 / elif age >= 18: / ticket_price = 12 / elif age >= 13: / ticket_price = 8 / else: / ticket_price = 5. If you put age >= 18 first, a 70-year-old would match that condition and never reach the senior check. This demonstrates why condition order matters in elif chains.

Question 4: APPLIED

You're building a simple login system. Given variables username and password, write a conditional that prints "Welcome, admin!" if the username is "admin" and the password is "secret123", prints "Wrong password" if the username is "admin" but the password is incorrect, and prints "User not found" otherwise. Use proper indentation and Boolean operators.
Show answer
This problem requires combining conditions with and: if username == "admin" and password == "secret123": / print("Welcome, admin!") / elif username == "admin": / print("Wrong password") / else: / print("User not found"). The order is critical: the if checks both conditions together. If the username is "admin" but the first check failed, we know the password must be wrong, so the elif only needs to check the username. The else handles all non-admin usernames.

Question 5: CRITICAL THINKING

Consider this code: x = 25 / if x > 10: / print("A") / if x > 20: / print("B") / else: / print("C"). What does this print, and why? Then rewrite it using elif so that only one letter prints. Explain the behavioral difference.
Show answer
The original code prints both "A" and "B". The first if x > 10 is an independent statement that prints "A". The second if x > 20 is a separate chain (not connected to the first if) and also evaluates to True, so it prints "B". The else belongs to the second if only. To print only one letter, rewrite as: if x > 20: / print("B") / elif x > 10: / print("A") / else: / print("C"). Notice the more specific condition (x > 20) must come first so it isn't shadowed by the broader condition (x > 10). This synthesis shows why using elif and ordering conditions carefully are both essential skills.

SUMMARY

Summary

Summary

Python's if/elif/else statements allow your programs to make decisions by testing Boolean conditions and executing the code block of the first matching branch. Each conditional keyword must end with a colon, and the code belonging to that branch must be indented by 4 spaces. The elif keyword provides additional conditions to check, while else serves as a catch-all that runs when no other condition was true.

Key principles to remember: use elif instead of multiple if statements when you need mutually exclusive branches, order your conditions from most specific to most general so broader conditions don't shadow narrower ones, and never mix tabs and spaces. Mastering these patterns gives you the foundation for every other indented structure in Python — from for loops to function definitions to class declarations.

Varsity Tutors • Python • If/Elif/Else Statements