Concepts / Conditional Logic

Conditional Logic

Python has no switch statement; this is a deliberate design choice, not an oversight.

  • Programming

The Missing Switch

If you are moving from C or C++ to Python, the absence of a switch statement may be one of your first surprises. Python does not omit switch accidentally. It deliberately uses other forms of conditional logic that can be more flexible and readable for the same branching problem.

The direct Python replacement for a C or C++ switch is an if, elif, else chain.

The important change is not merely a spelling difference. C and C++ switch statements can fall through from one case to another. Python if, elif, else chains are mutually exclusive: after one branch executes, the entire chain ends.

Tracing a Branch Chain

Python evaluates an if, elif, else chain from top to bottom. It checks the if condition first. If that condition is false, it checks the next elif condition. It continues in sequence until one condition is true. The matching branch executes, and Python leaves the entire chain without evaluating later branches.

evaluatetruefalsetruefalsebranch completebranch completebranch completecommandcommand == startstart actionstop actionleave chaincommand == stopdefault action
How does Python evaluate each condition in sequence, and where does control flow go after the first true condition?

command = "stop" if command == "start": action = "starting" elif command == "stop": action = "stopping" else: action = "unknown command" print(action)

What do you think happens?

What value will action have after this chain runs with command set to stop?

  • starting
  • stopping
  • unknown command
  • Both stopping and unknown command
Reveal answer

Answer: stopping

The first condition is false, the second condition is true, and the chain ends after that branch executes. Python does not fall through to the else branch.

Translating Switch Cases

A C or C++ switch selects a branch from the value of one expression. In the direct Python translation, the if tests the first possible value, each elif corresponds to another case, and else corresponds to default. The break behavior is represented by the fact that an if, elif, else chain stops after its first matching branch; no separate break is needed to prevent fall-through.

selectsoften followed byotherwiseif falseif trueif trueif falsemaps tomaps toautomatic equivalentswitchcase valuebreakif conditionelif conditionchain exitdefaultelse
How do a C or C++ switch, case matches, break statements, and default branch map onto an equivalent Python if, elif, else chain?

Mapping Menu Selection

Translate a multi-branch selection for the values 1, 2, and all other values into Python.

Identify the cases: Treat the possible input values as the branches that need separate actions.

Write the first branch: Use if to test the first value.

Add remaining branches: Use elif for each additional specific value.

Add the fallback: Use else for the behavior that applies when none of the listed values matches.

Check branch completion: No break statement is needed. Once a branch executes, the Python chain ends.

selection = 2 if selection == 1: result = "create" elif selection == 2: result = "open" else: result = "unknown selection"

Dictionary Dispatch

When there are many branches, or when the selected behavior needs to be changed dynamically, a dictionary can map keys to functions. This pattern is called dictionary dispatch. Instead of checking conditions one after another, the input key selects the corresponding function from the dictionary, and that function performs the action.

lookupcontainscontainsmatches keyinvokescommandstopactionskey to functionstartstart_actionstop_actionstoppingstopstop_action
How does an input key move through a dictionary lookup to select and invoke the corresponding action?
python
Output (expected)
stopping

The dictionary version separates the branch table from the action implementations. That makes it modular: a new command can be associated with another function by adding a mapping. The source describes dictionary dispatch as a high-performance alternative for many branches or dynamic dispatch.

Choosing a Branching Style

Questionif, elif, elseDictionary dispatch
What does it represent?A sequence of conditions evaluated from top to bottomA mapping from keys to functions
When is it clearest?When conditions contain logic or the number of branches is smallWhen many keys select separate actions
How are actions organized?Directly inside each branchIn functions referenced by the dictionary
What does it support well?Flexible conditions and a fallback branchFast, modular branching and dynamic dispatch
What replaces switch cases?if and elif conditionsKeys in the dispatch dictionary

Prefer an if, elif, else chain when the conditions themselves are important, when they are not simple key matches, or when a short direct translation is easiest to read. Consider dictionary dispatch when many branches are keyed by values, when actions should be modular functions, or when the mapping needs to support dynamic dispatch.

Mistakes with Branches

  • Looking for a switch statement in Python

    Python does not provide a switch statement; its absence is a deliberate language design choice.

    Fix: Translate the cases into an if, elif, else chain, or use dictionary dispatch when key-to-function mapping is appropriate.

  • Adding a break statement to an if, elif, else chain

    The Python chain is already mutually exclusive. Once one branch executes, the entire block exits.

    Fix: Let the chain finish naturally. No separate break is needed to prevent fall-through.

  • Expecting later branches to run after a match

    Python does not fall through from one branch to another.

    Fix: Treat the first true condition as the selected branch and trace control directly to the end of the chain.

  • Using a long conditional chain when the decisions are simple key-to-action mappings

    A long chain can be less modular for many branches or dynamic dispatch.

    Fix: Consider a dictionary that maps each key to its corresponding function.

Practice the Translation

EASY

A C or C++ switch has branches for the values "add" and "remove", plus a default branch for every other value. Write the equivalent Python if, elif, else chain. Then describe why no break statement is required.

Hints
  • Use if for the first value.
  • Use elif for the second value.
  • Use else for the default behavior.
  • The Python chain exits after the first matching branch.
MEDIUM

Suppose a program has many command names, and every command name selects a separate function. Decide whether an if, elif, else chain or dictionary dispatch better expresses the design. Explain your choice using the ideas of modularity, number of branches, and dynamic dispatch.

Hints
  • A dictionary can map keys to functions.
  • The source identifies dictionary dispatch as useful for many branches or dynamic dispatch.
  • An if, elif, else chain remains the direct and readable choice when the conditions themselves are central.

Key Takeaways

  1. Python has no switch statement, and this is a deliberate design choice.
  2. Use if, elif, else as the direct replacement for C or C++ switch logic.
  3. A Python branch chain evaluates conditions in sequence and stops after the first true branch, so there is no fall-through.
  4. Use else as the equivalent of a default branch when no earlier condition matches.
  5. Dictionary dispatch maps keys to functions and is useful for fast, modular branching with many branches or dynamic dispatch.

Key Takeaways

  • Python replaces switch statements with general conditional logic rather than a dedicated switch construct.
  • An if, elif, else chain directly maps conditions to branches and prevents fall-through automatically.
  • The first true branch ends the chain, so later branches are not executed.
  • Dictionary dispatch maps input keys to functions and suits many-branch or dynamic-dispatch designs.
  • Choose the structure that makes the conditions, actions, and branching purpose clearest.