Concepts / Nested Conditional Statements

Nested Conditional Statements

A multiway branch built from if, else if, and else executes one and only one of its statements.

  • 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…

Choosing One Outcome Out of Several

Many programs need to choose exactly one action from several possibilities. Imagine a thermostat-style program that prints one message for cold weather, another for pleasant weather, and another for hot weather. The program should show one message, not all three. Java handles this kind of decision with a multiway branch, built from an if statement, one or more else if clauses, and an optional final else.

A multiway branch is a single statement that represents a choice among several outcomes. Its defining property is that one and only one of its statements is executed. Before reading the rest of this article, make a prediction about the code below.

What do you think happens?

If temperature is 42, which message is printed, and are the later conditions checked?

  • Cold weather only, and the later conditions are not checked

  • Pleasant weather only, because 42 is in the middle range

  • All three messages, because every condition is tested

  • Nothing, because no condition is an exact match

Reveal answer
Answer:

Cold weather only, and the later conditions are not checked

The first test, temperature < 50, is true for 42. The computer prints the cold message and then jumps to the end of the whole chain, so the remaining tests and statements are skipped.

Tracing a Multiway Branch Top to Bottom

The computer does not run every clause of a multiway branch. It works through the boolean expressions in order, from top to bottom, and stops at the first one that evaluates to true. The rest of the chain is never looked at once a match is found. Here is an original example with the same structure as the thermostat program, using a temperature threshold of 50 and a second threshold of 75.

java
Output
Cold weather
Notes on the code
  • The first condition is tested first, and it is true for 42
  • The else if condition is never evaluated for this input
  • The final else is not reached

The figure below shows the same rule as a flowchart. Control enters at the first test. A true result sends control to one print statement and then to the end. A false result moves control to the next test, and only a false result at that second test reaches the final else. Each path ends after exactly one print statement. The path highlighted is the one taken when temperature is 42.

temperature < 50Cold weatherprinted, then chain endsPleasant weatherskipped for 42temperature < 75skipped for 42Hot weatherskipped for 42truefalsetruefalse
Which test is checked first for temperature 42, which tests are skipped, and where does execution stop?

Stopping at the First True Test

The stopping rule is sometimes called short-circuit behavior, and it is the key to understanding the construct. When a test is true, the computer executes the statement attached to that test and then jumps to the end of the whole chain. Every later test is skipped, and so is every later statement. Reordering the tests therefore changes which message can ever be printed.

The final else is the fallback for the case where no test is true. It is optional. If it is left out and every boolean expression is false, none of the statements in the chain are executed. The program simply continues with whatever comes after the chain.

Worked example

Tracing temperature 60 through the chain

Using the thermostat chain with thresholds 50 and 75, which message is printed when temperature is 60?

  1. 1
    Test 1

    Check temperature < 50. Since 60 is not less than 50, the test is false.

  2. 2
    Move to Test 2

    Because the first test was false, control moves to the else if test.

  3. 3
    Test 2

    Check temperature < 75. Since 60 is less than 75, the test is true.

  4. 4
    Execute and stop

    The computer prints Pleasant weather and jumps to the end. The final else is never reached.

Result

Pleasant weather is printed, and exactly one statement runs.

The same pattern extends to any number of cases. Each additional else if adds one more test, and the chain still executes exactly one statement. The general form has the following structure, with the tests and statements written as placeholders.

java
Notes on the code
  • Each test is checked in order from top to bottom
  • The first true test selects its statement
  • The final else runs only when every earlier test is false

Why Test Order Matters

Because the computer stops at the first true test, the order of the tests decides which outcomes are even possible. Consider a grading program where one test checks whether a score is at least 60 and another checks whether it is at least 90. Both conditions are true for a score of 95. Whichever one is written first wins.

Before
int score = 95;
if (score >= 60) {
    System.out.println("Pass");
} else if (score >= 90) {
    System.out.println("Excellent");
}

The 60 test comes first, so 95 prints Pass and the 90 branch is never reached

After
int score = 95;
if (score >= 90) {
    System.out.println("Excellent");
} else if (score >= 60) {
    System.out.println("Pass");
}

The 90 test comes first, so 95 prints Excellent and the 60 branch is never reached

score >= 60Passprinted for 95Excellentunreachable for 95score >= 90never reached for 95truefalsetrue
If the score checks are written as at least 60 first and then at least 90, why does a score of 95 never reach the 90 branch?

The diagram makes the problem visible. The 90 test sits behind the 60 test, and any score that passes the 60 test stops the chain before the 90 test is looked at. The fix is to place the more specific or higher threshold first, so that its matching statement is reached before any broader test can claim the value.

Separate ifs Versus an else if Chain

A common source of confusion is writing several independent if statements where an else if chain was intended. A chain of separate if statements tests every condition, so more than one of them can be true and more than one statement can run. The else if connection is what gives the construct its one-and-only-one behavior.

java
Output
Pass
Excellent
Notes on the code
  • Both if statements are independent
  • Both conditions are true for 95, so both messages print
if score >= 60true, prints Passif score >= 90true, prints Excellentif score >= 60true, prints Passelse if score >= 90skipped after a true testthen testedonly if first is false
How does the path of execution differ between three independent if statements and one if / else if chain, and why can two branches run for one input?

In the first column, both tests are evaluated and both messages appear, which is correct behavior for independent checks but wrong for a choice among outcomes. In the second column, the second test is only considered when the first is false, so the output is one message. Use separate if statements only when several actions can genuinely apply at once, and use an else if chain when exactly one outcome should be selected.

Mistakes That Break One-and-Only-One

The multiway guarantee depends on the chain being connected through else. When that connection is broken, the computer no longer stops at the first true test, and the output can differ from what you expect. The following mistakes are the most common sources of such surprises.

  • Common mistake

    Replacing an else if with a plain if

    What it looks like
    if (score >= 60) { ... } if (score >= 90) { ... }
    Why it fails

    Each if is tested independently, so several branches can run for one input.

    Do this instead

    Connect the tests with else if so that only the first true test runs its statement.

  • Common mistake

    Ordering overlapping tests carelessly

    What it looks like

    Testing score >= 60 before score >= 90

    Why it fails

    A score of 95 matches the first test, so the 90 branch is never reached.

    Do this instead

    Place the more specific or higher threshold first when ranges overlap.

  • Common mistake

    Assuming the final else always runs

    What it looks like

    A chain with no else where every test is false

    Why it fails

    The final else is optional. If it is omitted and all tests are false, nothing in the chain executes.

    Do this instead

    Add a final else when every input should produce some output, or confirm that doing nothing is intended.

  • Common mistake

    Writing a test that can never be reached because an earlier test already covers its values

  • Common mistake

    Forgetting that a true test skips every later statement, not just the one it is attached to

Practice Tracing a Chain

MEDIUM

Using the thermostat chain with thresholds 50 and 75, predict the output for temperature values 30, 50, 74, and 75. For each value, write down which tests are checked, which are skipped, and which message is printed. Then check your reasoning against the rule that the first true test wins.

Hints
  • Start at the first test and stop as soon as one is true
  • A value that equals a threshold is not less than that threshold
  • Check whether the value 75 passes the less than 75 test
HARD

A program checks water temperature with three branches: below 0 prints Frozen, below 100 prints Liquid, and otherwise prints Steam. Write the else if chain and then explain what happens if the two tests are swapped so that the 100 test comes first.

Hints
  • Write the first test, then else if, then a final else
  • Trace a value such as 150 through the swapped order

Key Takeaways

  • A multiway branch built from if, else if, and else executes one and only one of its statements.
  • The computer evaluates boolean expressions from top to bottom and stops at the first one that is true, skipping every later test and statement.
  • The final else runs only when every test is false; if it is omitted and all tests are false, nothing in the chain executes.
  • Test order decides which outcomes are possible, and separate if statements can run several branches for one input where an else if chain runs only one.