Lingnan University · FACULTY OF COMPUTER SCIENCE

CDT501 Chap.6 Loops, Dictionaries and State

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

Loops, Dictionaries and State

Prove progress and make lookup exact

This chapter represents a loop as initial state, condition, body and update. It selects for when an iterable already describes the repetitions and while when continuation depends on changing state. Nested-loop counts are separated from filtered outputs, while dictionaries introduce exact keys, replacement, safe missing-key decisions and nested data shapes.

In this chapter

What this chapter covers

  • 01

    While-loop progress and termination

  • 02

    For loops and stop-exclusive ranges

  • 03

    Nested loop counts

  • 04

    Dictionary keys and updates

  • 05

    Nested collection shapes

Worked example · free

Repair a loop that stalls

Q [6 marks]. A counter increments only on even passes and becomes stuck at one. Explain and repair the progress measure. Marks shown are AskSia practice guidance and are not official marking points.
The return arrow carries updated state.The return arrow carries updated state. Initialisation happens once, the condition is checked before each pass, and the body must move the program toward the false exit.A terminating loop must move state toward a false conditioninitialisecondition?bodyupdate statetruerepeatfalse: leave loop
The return arrow carries updated state. Initialisation happens once, the condition is checked before each pass, and the body must move the program toward the false exit.
  • 2Trace the first two passes.
  • 2Name the state controlling termination.
  • 2Move the update or select a for loop.
Zero advances to one, then the odd branch skips the update and the condition remains true forever. Update the counter on every path that returns to the condition. Because the complete sequence is known, a for loop over range five expresses the bounded repetition more directly.
Sia tip — Name what gets closer to done on every pass.
Glossary

Key terms

Loop Condition
The Boolean test deciding whether another pass of a while loop begins.
Progress Measure
State that changes on every repeated path toward termination.
Range
A generated integer sequence whose start is included and stop is excluded.
Nested Loop
A loop executed inside another loop, often examining combinations of values.
Key Error
The exception raised when direct dictionary lookup requests an absent key.
FAQ

Loops, Dictionaries and State FAQ

How do I know whether a while loop terminates?

Identify the state used by the condition and show that every path through the body moves it toward making the condition false. If one branch leaves the progress measure unchanged, the loop can stall. Trace the first few passes and the final intended pass before trusting the implementation.

Why does range stop before the stop argument?

The stop-exclusive convention aligns ranges with sequence lengths and slices. Range three produces zero, one and two, the valid indices for a three-element sequence. Write the intended first and final values, then select start, stop and step rather than adjusting a bound until one sample works.

When should dictionary get be avoided?

Get is useful when an absent key has a defined default meaning. It can hide a spelling or capitalisation defect when the key is required. Validate the expected keys first, preserve missingness as evidence and introduce a default only after the domain defines what absence should mean.

What is the difference between an empty range and an infinite loop?

An empty range gives a for loop zero planned iterations because its start, stop and step describe no reachable values. The program continues immediately after the loop. An infinite while loop begins iterating but never makes its condition false, so execution remains in the loop unless interrupted.

Diagnose them differently: print or inspect the range values before the loop, but trace the condition variable before and after every path through a while body. A zero-iteration loop can be correct for empty input, whereas an infinite loop usually signals a missing state update or an invariant condition. Tests should include empty, one-item and several-item cases so absence of output is not mistaken for successful processing.

Study strategy

Assessment move

Trace while loops in a table containing the condition before the pass, output and state after the update. Write the values a range produces rather than only its arguments. For nested loops, count examined pairs separately from printed results. Build dictionary exercises that distinguish an existing key update, a new key and a misspelled required key.

For every while loop, circle the progress measure and inspect every branch that returns to the condition. If a branch leaves the measure unchanged, predict the first state at which execution stalls. Move the update only after stating whether it should occur on successful, failed or every pass. Replace a counter-controlled while loop with a for loop over a range and compare which facts each form makes explicit.

Practise ascending and descending ranges, listing all generated values so the excluded stop and step sign are visible. With nested loops, make a grid of outer and inner values. Count the cells examined, then apply a condition and separately count the results retained. This prevents a filtered output count from being mistaken for reduced loop work.

Shift one print or append statement across an indentation level and predict whether it runs once per pair, once per outer item or once after all iteration. For dictionaries, create a small record and perform three operations: replace an existing value, add a new key and request a differently capitalised key. Explain why only the last raises a key error.

Compare direct lookup with get, and permit a default only after stating what absence means in the problem. End with a nested dictionary-of-lists example. Write the shape in words, test an absent outer key and an empty inner list separately, and assign each access step to a descriptive variable before composing them.

Working through Loops, Dictionaries and State in CDT501? Sia is AskSia’s AI Computer Science tutor — ask any CDT501 Loops, Dictionaries and State question and get a clear, step-by-step explanation grounded in how CDT501 is taught and assessed. Read this chapter free, then take your hardest questions to Sia.

A+Everything unlocked
Unlocks this Bible + all 9 of your Lingnan University subjects - and 1,000+ Bibles across every Australian university.
Sia - your CDT501 tutor, unlimited, worked the way the exam marks it
The full 4-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
CDT501 · Computer Systems and Programming Basics - independent study guide on the AskSia Library. More Lingnan University subjects · Microeconomics across all universities