City University of Hong Kong · FACULTY OF INFORMATION TECHNOLOGY

IS5312 Chap.4 For Loops, Errors and Files

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

For Loops, Errors and Files

This chapter connects iteration with persistent data. It covers range objects, positive and negative steps, iteration across strings and collections, nested loops, and the different effects of pass, continue and break. Error diagnosis is split into syntax, runtime and logic failures.

File work follows a deliberate connection lifecycle: open in the correct mode, read with the appropriate method, transform data, write or append, and close reliably.

In this chapter

What this chapter covers

  • 01

    For loops and range boundaries

  • 02

    Nested loops and control statements

  • 03

    Syntax, runtime and logic errors

  • 04

    Text-file reading methods

  • 05

    Writing, appending and CSV transformation

Worked example · free

Add a ratio field to a CSV row

Q [9 marks]. The marks shown are an AskSia study allocation and are not the University marking scheme. Transform a text row into typed fields, calculate a ratio and write a new row.
Reading changes the connection state.Reading changes the connection state. Each line read advances the pointer, exhaustion returns empty text, and closing guarantees the connection is released.A file pointer advances as lines are readopenreadlinemovesempty textcloseread() takes all remaining text; readlines() returns the remaining lines as a list.
Reading changes the connection state. Each line read advances the pointer, exhaustion returns empty text, and closing guarantees the connection is released.
  • 3Split and validate the fields.
  • 3Convert and calculate the ratio.
  • 3Format and write a new row.
Strip the newline, split on commas, keep the label as text and convert the two quantities. Divide in the stated direction, format the result and write to a separate output file while testing. The score shown belongs to this independent AskSia exercise and is not a University allocation.
Sia tip — Keep the original file unchanged until the output is verified.
Glossary

Key terms

Range Object
An iterable arithmetic progression whose stop value is excluded.
Runtime Error
A failure raised when execution reaches an invalid operation.
File Pointer
The current position from which the next file read begins.
FAQ

For Loops, Errors and Files FAQ

Why is the range stop missing?

Range stops before its stop argument, matching Python slice boundary behaviour. Write the first two generated values and step direction to verify the boundary before looping.

Why is the second read empty?

The first read may already have advanced the pointer to the end of the file. Reopen or reposition deliberately when a second pass through the same content is required.

How do I distinguish logic from syntax errors?

A logic error runs and returns the wrong result, while a syntax error prevents parsing. Reproduce the smallest failing input and compare each intermediate value with a hand trace.

Study strategy

Assessment move

Practise iteration by writing the sequence before writing the loop. For every range call, list the first two values, the excluded stop and the step direction. Test ascending, descending and empty ranges, then translate each into an equivalent while loop to expose the update that range manages automatically.

Iterate over the same string once by item and once by index, explaining why the index form is needed only when position matters. Add a nested-loop exercise such as a small multiplication grid and predict the total body executions from the two sequence lengths. For error diagnosis, keep three separate routines. A syntax failure is checked through colons, indentation and matching delimiters.

A runtime failure is reproduced with the input that reaches the invalid operation and inspected for type, conversion, path or zero-divisor problems. A logic failure is compared with a hand-computed case and traced until the first wrong state. Do not change code from one category while investigating another. File practice begins with an exact expected file.

Create a three-line text file, read it once with read, once with repeated readline calls and once with readlines, recording the returned type, newline characters and pointer position. Reopen between experiments so exhaustion is not mistaken for missing data. Write to a new output file and verify the exact bytes students can see: row count, order, delimiters, decimal formatting and line endings.

For CSV work, describe one row as a schema before coding. Mark which fields remain text, which require numeric conversion and what unit a calculated field will have. Process the header separately and retain the original input while testing. Practise append mode only after write mode is understood, and inspect whether repeated runs intentionally add records or accidentally duplicate them.

Finish with an original transformation that reads labelled quantities, calculates one ratio and writes a new column. Use a ratio whose direction can be checked in words so reversing numerator and denominator becomes obvious. During lab-test revision, treat the file as program state outside memory: opening chooses the mode, reading advances the pointer, writing changes persistent data, and closing completes the operation.

Every file answer should state all four actions. Add a controlled fault-injection round. Remove one colon to observe a syntax failure, supply a nonnumeric field to trigger a runtime conversion failure, and reverse a ratio while keeping the program executable to create a logic failure. For each fault, record the earliest evidence that identifies its family and the smallest repair.

Next, trace a file connection through two consecutive reads and label the pointer position after each operation. Repeat after reopening so the difference between persistent file contents and temporary connection state is explicit. For output verification, read the newly written file back into the program and compare its row count, header and calculated field against expected values.

Include an empty input file and a file with only a header. End with a descending range and a nested loop whose body count can be predicted by multiplication. These cases connect iteration bounds to persistent data processing and make off-by-one errors visible before they affect a complete transformation.

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