Concepts / Introduction to the Switch Statement

Introduction to the Switch Statement

A switch statement can branch on a String value, letting the program react to a unit name typed by the user.

  • Programming
Interactive lab

Try it: if / elif / else

How Python tests if / elif conditions from the top, runs only the first true branch, and how and / or stop evaluating as soon as the answer is known (short-circuiting).

How it works

  1. Python evaluates the if condition first.
  2. If it is False, it tries each elif in order; the first True one runs and the rest are skipped without being tested.
  3. If none is True, the else branch runs.
  4. and stops at the first False, or stops at the first True — the right side may never be evaluated.

Default run (5 steps): score = 84; A = 90, B = 80, C = 70. Python tests the conditions from the top. … print(grade) shows B.

Educational simulation

Loading the simulation…

Why Measurements Need a Common Unit

Suppose a program asks a user for a length and then needs to perform a calculation with it. A user might type a distance in feet, another in yards, and another in miles. The program cannot simply add those numbers together. A value of 3 in feet and a value of 3 in yards describe very different distances, so the numbers alone do not tell the program how far anything really is. Before any calculation can happen, each measurement must be translated into one standard unit. In this article, that standard unit is the inch.

What do you think happens?

If one measurement is 3 feet and another is 3 yards, which one is the longer distance?

  • 3 feet

  • 3 yards

  • They are the same length

Reveal answer
Answer:

3 yards

One foot is 12 inches and one yard is 36 inches. So 3 feet is 36 inches, while 3 yards is 108 inches. The same number 3 describes a much longer distance when the unit is yards.

The program therefore has two jobs. It must read the number and the unit name, and then it must choose the correct conversion for that unit. The switch statement is the tool that makes this choice, and in the version studied here it makes the choice by examining text rather than a number.

Following One Input Through the Switch

Before reading the rules, follow the program's path for a single input. The user types a unit name, and that text is stored in a variable named units. The switch compares the text against the labels in each case. The program runs the first case whose label matches, and it skips the rest. As you follow the path, watch three things at each step: which lines run, which branch was selected, and what value is now stored for inches.

Read unit namestored in unitsswitch on unitscompare to case labelscase feetmultiply by 12Inches storedfor matched unitcase yardsmultiply by 36case milesmultiply by 12 then 5280default caseprint illegal unitProgram endsfor unmatched unitfeetyardsmilesno label matches
When the user types feet, yards, or miles, which case label is matched, and where does the program jump next?
Worked example

Tracing the input yards

The user enters the number 3 and the unit name yards. What value does the program store for inches?

  1. 1
    Read the unit

    The variable units holds the text yards.

  2. 2
    Compare against the labels

    The switch compares the text against each case's labels and finds the case whose label is yards.

  3. 3
    Apply the conversion factor

    One yard is 36 inches, so the case multiplies the measurement by 36. Three times 36 is 108.

  4. 4
    Store the result

    The variable for inches now holds 108.

Result

The yards case runs and 108 inches is stored. The feet and miles cases are skipped.

EASY

Trace the input 3 feet with the same method. Name the case that runs, write the factor it uses, and state the value stored for inches. Check your answer against the factor of 12 for feet.

Hints
  • Ask which case label matches the text feet.
  • Multiply 3 by the factor for that case.

How a Switch Chooses a Case

A switch statement checks the value of a variable and chooses one case to run. In the string version, the variable holds text rather than a number. The program runs the first case whose label matches the text, and skips the rest. This is what allows the program to react to a unit name typed by the user.

There is more than one way to ask the user for a unit. One design shows a menu of numbered options and reads a choice number. A second design asks the user to type the unit's name, such as inch or feet, and uses that text directly to decide what to do. The text-based design is the focus here because it shows how a switch can work with strings rather than only with numbers.

Converting Feet, Yards, and Miles to Inches

Each unit other than the inch needs a conversion factor, which is the number of inches in one of that unit. A measurement is converted by multiplying the number by the factor for its unit. The source uses three factors. One foot is 12 inches, so a measurement in feet is multiplied by 12. One yard is 36 inches, so a measurement in yards is multiplied by 36. A mile is 5280 feet, and each foot is 12 inches, so a mile is multiplied by 12 and then by 5280 in the source's code, which gives a factor of 63360.

Rule

Formula, step by step
  1. 1
    measurement is the number the user typed, such as 3
  2. 2
    conversion factor depends on the unit: 12 for feet, 36 for yards, 12 times 5280 for miles
  3. 3
    the product is the same distance expressed in inches
UnitInches per unitFactor applied to the measurement
feet12multiply by 12
yards36multiply by 36
miles12 times 5280multiply by 12 then by 5280

Conversion factors used to translate each unit into inches

feetfactor 12yardsfactor 36milesfactor 12 times 5280inchesfactor 1, already standard
Which multiplier is associated with each unit name, and how does each unit map to a common inch value?

When No Label Matches

The switch has a default case, which runs when no other label matches. The source uses it to catch any unit name the program does not recognize. Typing a unit such as furlong, or misspelling feet as fete, matches no label, so the default branch runs. That branch prints a message saying the unit is illegal and then ends the program. Because the default branch ends the program, no conversion is performed and no inch value is produced for that input.

Worked example

Tracing the input fete

The user enters the number 3 and the unit name fete. What happens?

  1. 1
    Read the unit

    The variable units holds the text fete.

  2. 2
    Compare against the labels

    fete does not match feet, yards, miles, inch, inches, or in.

  3. 3
    Take the default branch

    No label matched, so the default case runs and reports an illegal unit.

  4. 4
    End the program

    The default branch ends the program, so no multiplication is performed.

Result

The program reports an illegal unit and stops. No inch value is stored.

How an If Statement Chooses a Path

Programs do not always perform every instruction. Sometimes they must choose a path. An if statement creates that choice by examining a boolean-valued expression. The expression is either true or false, and that result determines which action the computer takes. The action is decided at the decision point, so only one result's action is carried out for a given run.

Boolean conditiontrue or falseTrue alternativeruns when trueNext statementexecution continuesAlternative afterelseruns when falsetruefalse
If the boolean condition is true, which block runs and which is skipped, and what changes when it is false?

In an if-else statement, the condition chooses one of two alternatives. When the condition is true, the statement before else runs and the statement after else is bypassed. When the condition is false, the first alternative is bypassed and the alternative after else is selected. The two display actions do not both occur.

Anatomy of an If-Else Statement

PartRoleWhat runs
Boolean expressionDetermines which path is selectedEvaluated to true or false
Statement before elseAlternative for a true resultRuns only when the expression is true
Statement after elseAlternative for a false resultRuns only when the expression is false

Parts of an if-else statement and their roles

When an if statement produces an unexpected result, inspect the decision in order. First identify the boolean expression. Next determine whether its value is true or false. Finally check which statement belongs to that result. Following these three steps lets you trace an if-else statement without running it.

Simple If Versus If-Else

An if statement does not always need an else clause. The one-way form is useful when the program should perform an action only for a true condition. If the expression is false, the contained statement is skipped, and control continues with whatever follows the if statement. An if-else statement, by contrast, always leaves exactly one alternative to run.

FeatureSimple ifIf-else
AlternativesOne action, or noneExactly one of two alternatives runs
When condition is falseContained statement is skipped and execution moves onThe alternative after else runs
When condition is trueContained statement runsThe statement before else runs; the alternative after else is bypassed
Typical useAct only in one caseChoose between two actions

Path differences between a simple if and an if-else

Mistakes Beginners Make

  • Common mistake

    Expecting a misspelled unit to produce a result

    What it looks like

    The user types fete, and the learner expects the feet factor to be used.

    Why it fails

    A label must match the typed text. fete matches no label, so the default case runs.

    Do this instead

    Trace the text against the labels first. An unmatched unit triggers the default case and ends the program.

  • Common mistake

    Adding measurements given in different units

    What it looks like

    Adding 3 feet and 3 yards as if both were 3 inches.

    Why it fails

    The same number describes different distances in different units.

    Do this instead

    Convert each measurement to inches first, then combine the inch values.

  • Common mistake

    Assuming both branches of an if-else run

    What it looks like

    Believing that a true condition runs the statement before else and then also runs the statement after else.

    Why it fails

    The decision picks one alternative, and the other is bypassed.

    Do this instead

    For each run, determine the value of the boolean expression and then run only the statement that belongs to that result.

  • Common mistake

    Expecting a false condition to do something in a simple if

    What it looks like

    Assuming a simple if with no else performs some action when its expression is false.

    Why it fails

    A simple if skips its contained statement when the expression is false and continues with what follows.

    Do this instead

    Check whether the statement has an else clause before deciding what runs on false.

Trace It Yourself

MEDIUM

Work through the switch for each input without running the program. For each one, name the branch that runs and write the value stored in inches, or state that the default branch runs. Inputs: inch, in, yards, miles, furlong.

Hints
  • inch and in both belong to the same case, which stores the measurement unchanged.
  • For miles, the factor is 12 times 5280.
  • furlong matches no label, so think about which branch handles unmatched text.
EASY

A user enters 2 and the unit name yards, and a second user enters 2 and the unit name fete. Trace both. Which one stores a value for inches, and what is that value?

Hints
  • Only the matched input reaches a conversion factor.
  • Two yards is two times 36.

Key Takeaways from the Path

  1. 1
    A switch statement compares the text in a variable such as units against case labels and runs the first matching case.
  2. 2
    Each unit is converted to inches with a factor: 12 for feet, 36 for yards, and 12 times 5280 for miles.
  3. 3
    A unit that matches no label runs the default case, which reports an illegal unit and ends the program.
  4. 4
    An if statement chooses a path from a boolean expression; an if-else runs exactly one alternative, while a simple if skips its statement when the expression is false.

At a glance

  • A switch statement compares a String value, such as a unit name typed by the user, against case labels and runs the first matching case.
  • Each unit is converted to inches by multiplying by its factor: 12 for feet, 36 for yards, and 12 times 5280 for miles.
  • An unmatched unit runs the default case, which reports an illegal unit and ends the program.
  • An if statement uses a boolean expression to choose a path; if-else runs exactly one of two alternatives, while a simple if skips its statement when the expression is false.