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.
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
- Python evaluates the if condition first.
- If it is False, it tries each elif in order; the first True one runs and the rest are skipped without being tested.
- If none is True, the else branch runs.
- 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.
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?
Reveal 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.
Tracing the input yards
The user enters the number 3 and the unit name yards. What value does the program store for inches?
- 1Read the unit
The variable units holds the text yards.
- 2Compare against the labels
The switch compares the text against each case's labels and finds the case whose label is yards.
- 3Apply the conversion factor
One yard is 36 inches, so the case multiplies the measurement by 36. Three times 36 is 108.
- 4Store the result
The variable for inches now holds 108.
The yards case runs and 108 inches is stored. The feet and miles cases are skipped.
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.
- 1measurement is the number the user typed, such as 3
- 2conversion factor depends on the unit: 12 for feet, 36 for yards, 12 times 5280 for miles
- 3the product is the same distance expressed in inches
| Unit | Inches per unit | Factor applied to the measurement |
|---|---|---|
| feet | 12 | multiply by 12 |
| yards | 36 | multiply by 36 |
| miles | 12 times 5280 | multiply by 12 then by 5280 |
Conversion factors used to translate each unit into inches
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.
Tracing the input fete
The user enters the number 3 and the unit name fete. What happens?
- 1Read the unit
The variable units holds the text fete.
- 2Compare against the labels
fete does not match feet, yards, miles, inch, inches, or in.
- 3Take the default branch
No label matched, so the default case runs and reports an illegal unit.
- 4End the program
The default branch ends the program, so no multiplication is performed.
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.
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
| Part | Role | What runs |
|---|---|---|
| Boolean expression | Determines which path is selected | Evaluated to true or false |
| Statement before else | Alternative for a true result | Runs only when the expression is true |
| Statement after else | Alternative for a false result | Runs 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.
| Feature | Simple if | If-else |
|---|---|---|
| Alternatives | One action, or none | Exactly one of two alternatives runs |
| When condition is false | Contained statement is skipped and execution moves on | The alternative after else runs |
| When condition is true | Contained statement runs | The statement before else runs; the alternative after else is bypassed |
| Typical use | Act only in one case | Choose 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 likeThe user types fete, and the learner expects the feet factor to be used.
Why it failsA label must match the typed text. fete matches no label, so the default case runs.
Do this insteadTrace 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 likeAdding 3 feet and 3 yards as if both were 3 inches.
Why it failsThe same number describes different distances in different units.
Do this insteadConvert each measurement to inches first, then combine the inch values.
Common mistake Assuming both branches of an if-else run
What it looks likeBelieving that a true condition runs the statement before else and then also runs the statement after else.
Why it failsThe decision picks one alternative, and the other is bypassed.
Do this insteadFor 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 likeAssuming a simple if with no else performs some action when its expression is false.
Why it failsA simple if skips its contained statement when the expression is false and continues with what follows.
Do this insteadCheck whether the statement has an else clause before deciding what runs on false.
Trace It Yourself
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.
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
- 1A switch statement compares the text in a variable such as units against case labels and runs the first matching case.
- 2Each unit is converted to inches with a factor: 12 for feet, 36 for yards, and 12 times 5280 for miles.
- 3A unit that matches no label runs the default case, which reports an illegal unit and ends the program.
- 4An 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.