Simple if Statements
A multiway branch built from if, else if, and else executes one and only one of its statements.
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…
Predicting the Message for One Input
Many programs must choose one action out of several possibilities. A thermostat-style program might print one message for cold weather, another for pleasant weather, and another for hot weather. Java handles this kind of choice with a multiway branch, built from an if statement, one or more else if clauses, and an optional final else. Before reading any further, make a prediction. Suppose the variable temperature holds 42, and you are looking at the three messages in a program like this one.
What do you think happens?
For temperature = 42, which message is printed by this chain: if (temperature < 50) cold message, else if (temperature < 80) pleasant message, else hot message?
Reveal answer
It is cold.
42 is less than 50, so the first test is true. The computer prints the cold message and then jumps to the end of the whole chain. The second test is never evaluated, and neither is the final else.
One Choice Among Several Outcomes
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. The computer does not run every clause. It works through the boolean expressions in order, from top to bottom, and stops at the first one that evaluates to true.
The word multiway matters. A simple one-way decision asks a single question and either runs a body or skips it. A multiway branch asks a series of questions, and the answers determine which of several bodies runs. Each additional else if clause adds one more possible outcome, but the rule stays the same: exactly one body runs for any given input.
How the Computer Walks the Chain
Control enters the chain at the first test. If that test is true, the computer executes the statement attached to it, then jumps to the end of the whole chain. Every later test is skipped, and so is every later statement. If the first test is false, control moves to the next test. Only when every test has been false does control reach the final else, if one exists. Each path through the chain ends after exactly one print statement.
The figure follows the same rule as the prose. A true result at the first test sends control straight to one print statement and then to the end. Only a false result at the first test leads to the second test, and only a false result there reaches the final else. The computer never tests a condition that comes after a true one, which is why the order of the tests decides which message can ever be printed.
Tracing Two Inputs Through a Chain
It is cold.- The first condition is tested before any other.
- Each else if clause is a further test, reached only when every earlier test was false.
- Every message is printed by a single
System.out.printlncall, so the output shows exactly which branch ran.
Tracing temperature = 80
Using the same chain, which message is printed when temperature is 80, and which tests are actually evaluated?
- 1Test the first condition
Is 80 less than 50? No, so the test is false and the computer moves to the next clause.
- 2Test the else if condition
Is 80 less than 80? No. The value sits exactly on the second threshold, and the strict less-than comparison makes this test false.
- 3Reach the final else
Both tests were false, so control falls through to the final else, which is the only remaining part of the chain.
- 4Execute one statement
The hot message is printed. Nothing else in the chain runs.
It is hot. Two tests were evaluated, and exactly one print statement ran.
Notice what the trace reveals. The input 42 needed only one test, while the input 80 needed two tests and then the final else. In both cases the number of tests can differ, but the number of executed print statements is always one. Tracing an input in this way lets you predict the output before running the program.
Anatomy of the Chain
The general form has one if clause, any number of else if clauses, and an optional final else. Each clause pairs a boolean expression with a statement. The tests and statements are placeholders in the general form, so the same pattern works for any number of cases. Each additional else if adds one more test, and the chain still executes exactly one statement.
- The if clause is required and always comes first.
- Each else if clause is optional and can be repeated as many times as needed.
- The final else is optional. Without it, a chain whose tests are all false executes nothing.
When No Test Is True
The final else acts as a catch-all branch. It runs only when every explicit test has been false. The inputs that reach it are the ones that none of the explicit conditions captured. If the final else is omitted, the situation changes: when every boolean expression is false, none of the statements in the chain are executed, and the program simply continues past the chain.
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 comparison below shows the difference between a row of separate if statements and a true else-if chain for the same temperature.
Common mistake Writing separate if statements where an else if was intended
What it looks likeif (temperature < 50) { System.out.println("It is cold."); } if (temperature < 80) { System.out.println("The weather is pleasant."); } else { System.out.println("It is hot."); }Why it failsThe first if and the second if are independent statements. For temperature = 42, both tests are true, so both messages are printed, and the chain no longer executes exactly one statement.
Do this insteadConnect the tests with else if so that the computer stops at the first true condition.
Common mistake Ordering tests so that an earlier broad test hides later cases
What it looks likeif (temperature < 80) { System.out.println("The weather is pleasant."); } else if (temperature < 50) { System.out.println("It is cold."); }Why it failsFor temperature = 42, the first test is already true, so the computer prints the pleasant message and never reaches the cold test. The cold case is effectively hidden.
Do this insteadPlace the most specific or most restrictive test first, so that narrower cases are checked before broader ones can match.
Common mistake Assuming a later test is evaluated even after an earlier one succeeded
Why it failsA true test sends control to the end of the chain. Every later test and statement is skipped, so no later condition can add a second message.
Do this insteadWhen tracing a chain, stop reading after the first true test and move to the end of the whole construct.
Predict Before You Run
Using the chain from the earlier example, where the cold test is less than 50, the pleasant test is less than 80, and the final else prints the hot message, predict the output for temperature = 50 and for temperature = 79. For each value, list which tests are evaluated, and say whether the output would change if the two else if tests were swapped.
Hints
- For temperature = 50, ask whether 50 is less than 50 first.
- A value of 79 is below 80, so consider which test is reached first and whether it is true.
- Swapping the tests changes which message the computer reaches first, so trace the swapped chain for the same values.
Summary of the Multiway Branch
At a glance
- 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 true one, skipping every later test and statement.
- If no test is true, the final else runs; if that else is omitted and all tests are false, nothing executes.
- Breaking the else connection or ordering tests carelessly can make several statements run or hide valid cases, so trace the path of each input before trusting the output.