IS5312 Chap.3 Conditions and While Loops
Conditions and While Loops
This chapter builds control flow from Boolean expressions. Relational operators create conditions, logical operators combine them, branches choose actions, and while loops repeat while a condition remains true.
It distinguishes independent if statements from exclusive elif chains, uses short-circuit evaluation as a safety guard, and treats loop termination as a proof about initial state, condition, update and exit rather than as trial and error.
What this chapter covers
- 01
Boolean and relational expressions
- 02
If, elif and else branching
- 03
Logical operators and short circuiting
- 04
While-loop state and validation
- 05
Break, continue and loop else
Worked example · free
Validate an even value in a range
- 3State the positive acceptance rule.
- 3Repeat while the rule is false.
- 2Test both boundaries and parity.
Key terms
- Boolean Condition
- An expression whose result is True or False.
- Short-circuit Evaluation
- Stopping a logical expression once its result is determined.
- Loop Invariant
- A statement that remains true at the start of every iteration.
Conditions and While Loops FAQ
When should I use elif?
Use elif when the categories are mutually exclusive and the first true condition should win. Put the narrowest or highest-priority category first and test every threshold explicitly.
How does short circuiting prevent errors?
Place a safety guard on the left of and so the risky expression is not evaluated when the guard fails. Python then skips the unsafe right-hand expression whenever the guard already determines a false result.
Why does a loop run forever?
At least one repeating path fails to change the state toward making the condition false, often because continue skips the update. A state table reveals the first iteration that fails to update or takes an unintended path.
Assessment move
Revise control flow by separating the Boolean from the structure that uses it. Begin with a requirement in words and write the valid set positively. For a bounded even number, identify the lower bound, upper bound and parity test separately, then combine them with and. Evaluate the Boolean on values below, at and above both boundaries before placing it inside a branch or loop.
Next, compare three program shapes: two independent if statements, an if and else pair, and an if, elif and else chain. Use an input that satisfies more than one rule so the difference between independent actions and mutually exclusive categories becomes observable. For compound conditions, practise short-circuit guards.
Put a safe check such as a nonzero divisor or sufficient string length on the left of and, then show why reversing the order can raise an error. Turn to while loops only after the condition is stable. Make a state table with columns for iteration number, state before the test, condition result, action, update and next state. Every repeating path must reach the update and move toward an exit.
Trace a normal completion, an immediate exit, a break, and a continue. If continue appears, highlight whether it can jump over the update. Use loop else with a search and explain why the no-match message runs after normal exhaustion but not after break.
Keep a small catalogue of common failures: overlapping branch ranges, a missing equality at a boundary, a Boolean reversed by not, an unchanged loop variable, a continue before the update, and a break on a partial match. For every failure, write the smallest input that reveals it. Finish by authoring two validation loops from scratch.
One should accept a menu choice from a fixed collection; the other should accept a numeric value satisfying a compound range rule. Separate text conversion errors from values that convert successfully but fail the semantic rule. During timed practice, do not begin by writing the loop body. Write initial state, condition, progress statement and exit on four lines first.
Those four lines are the proof that the loop can perform the required work and terminate. Add a branch-partition exercise in which every possible input belongs to exactly one category. Draw the intervals on a number line, mark inclusive endpoints and choose one test immediately below, on and above each boundary. Record which branch runs for every test; a gap or overlap then becomes visible before code is edited.
For loops controlled by sentinels, distinguish the sentinel from valid data and decide whether it is processed or only stops repetition. Trace the state immediately before and after the sentinel arrives. For a counter-controlled loop, write an invariant describing completed work, such as the number of valid items already processed and the total they contributed.
Check that the invariant is true after initialisation and preserved by every repeating path. Finally, rehearse one continue case by moving the update above the continue and one break case by writing the normal-exhaustion action separately. Explaining why those placements terminate correctly is stronger preparation than recognising the keywords in a finished program.