City University of Hong Kong · FACULTY OF INFORMATION TECHNOLOGY

IS5312 Chap.3 Conditions and While Loops

- one subject, every graph, every model, every mark
5 Chapters5-page Bible
Our own words - no uploaded lecturer files
Updated for this semester
Chapter 3 of 6 · IS5312

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.

In this chapter

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

Q [8 marks]. The marks shown are an AskSia study allocation and are not the University marking scheme. Accept only an even integer from 10 through 60 inclusive.
The same Boolean can drive two different structures.The same Boolean can drive two different structures. A branch chooses once, while a loop returns to the condition after updating the program state.A condition chooses a branch or repeats a bodyconditionTrue: run bodyFalse: take exitOnly a loop sends control back to test again.
The same Boolean can drive two different structures. A branch chooses once, while a loop returns to the condition after updating the program state.
  • 3State the positive acceptance rule.
  • 3Repeat while the rule is false.
  • 2Test both boundaries and parity.
Accept when 10 is less than or equal to the value, the value is at most 60, and the remainder after division by two is zero. Repeat while that compound condition is false. The displayed score is independently assigned for AskSia practice, not copied from University marking criteria.
Sia tip — Write the valid set positively, then negate it for repetition.
Glossary

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.
FAQ

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.

Study strategy

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.

A+Everything unlocked
Unlocks this Bible + all 31 of your subjects at City University of Hong Kong, plus 1,000+ more Bibles across the AskSia library.
Sia - your IS5312 tutor, unlimited, worked the way the exam marks it
The full 5-page Bible + practice bank with worked solutions
Chrome extension - sync your LMS so Sia knows your deadlines
Bilingual EN / Chinese on every Bible and every Sia answer
$0.99 Trial
30-day money-back · cancel in one tap · how it works