Concepts / For Loops and Iteration

For Loops and Iteration

Write a program that prompts the user for a filename, opens the file, and prints each line in uppercase using the upper() string method.

  • Programming
Interactive lab

Try it: Loop Tracer

How a Python for loop visits each item in turn, and how an accumulator variable (a total, a count, a best-so-far or a result list) changes on every iteration.

How it works

  1. Initialise the accumulator before the loop.
  2. Each iteration, the loop variable takes the next value from the list.
  3. An if inside the loop decides whether to update the accumulator.
  4. After the last item the loop ends and the accumulator holds the answer.

Default run (13 steps): values = [4, 9, 2, 7, 5]. Run the loop one statement at a time. … The loop has used every value. print(total) shows 27.

Simplified: A model of five fixed loop programs (sum, count, maximum, minimum, filter) run on your list — it steps the program exactly as Python would, but it does not run Python.

Educational simulation

Loading the simulation…

From Filename to Uppercase Output

A file-processing program can combine three fundamental skills: opening a file, iterating through its contents, and transforming the data. In this lesson, the program asks the user for a filename, reads the file one line at a time, converts each line to uppercase, prints the result, and closes the file when processing is complete.

python

The statements run in a fixed sequence. The input call gets the filename. The open call makes the file contents available through file_object. The for loop processes the file line by line. The upper() method transforms the current line, and print displays the transformed text. After the loop finishes, close releases the file resource.

filenamefile objectcurrent lineuppercase linenext iterationno lines remainFilename promptOpen fileFor loopOne line at a timeupper()Transform current linePrint lineClose fileAfter loop
What happens from the filename prompt through file processing and closing?

One Line per Iteration

A file object can be used directly in a for loop. Each time the loop repeats, Python automatically reads one line from that file object and assigns that line to the variable line. The loop continues until all lines have been read. The entire file is therefore processed as a sequence of individual lines rather than as one operation.

read one linerepeatrepeatno lines remainfile_objectRemaining file contentslineFirst linelineSecond linelineThird lineLoop endsAll lines read
How does the for loop obtain one line at a time, and when does iteration stop?

The important state change is the value stored in line. On the first iteration, line contains the first file line. On the next iteration, line contains the second file line, and so on. The loop variable is reused for each iteration, so the current value changes while the loop progresses through the file.

Transforming the Current Line

The upper() string method takes a string and returns a new string with lowercase letters converted to uppercase. Digits, punctuation, spaces, and special characters remain unchanged.

In the loop, line.upper() applies the transformation to the line currently being processed. The original line is read first, the uppercase version is produced next, and the transformed value is passed to print. This places the transformation between file reading and output.

lineuppercase resulthello worldCurrent file lineupper()Convert lowercase lettersHELLO WORLDPrinted line
How does each line move from the file through upper() to the output?
upper()python rocksBefore upper()PYTHON ROCKSAfter upper()
What changes in the current line when upper() is applied?

Tracing Three File Lines

Following the loop

Trace the program when the file contains the three lines hello world, python rocks, and file i/o.

First iteration: The file object provides hello world followed by a newline. Calling upper() produces HELLO WORLD followed by that newline, and the transformed line is printed.

Second iteration: The loop provides python rocks. Calling upper() produces PYTHON ROCKS, which is then printed.

Third iteration: The loop provides file i/o. Calling upper() produces FILE I/O, which is then printed.

Completion: After the third line has been processed, the file has no more lines. The loop ends and the program closes the file.

The output contains the same sequence of lines with their letters converted to uppercase: HELLO WORLD, PYTHON ROCKS, and FILE I/O.

next iterationnext iterationend of filehello worldupper() → HELLO WORLDpython rocksupper() → PYTHON ROCKSfile i/oupper() → FILE I/ONo lines remainLoop stops
How does the current line change as the loop repeatedly transforms and prints it?

A line read from a file can include its newline character. The trace should therefore treat the newline as part of the string while the line is being processed. The upper() method changes the letters but does not remove the newline, punctuation, spaces, or other non-letter characters.

Diagnosing Unexpected Output

  • Applying upper() outside the loop

    The transformation must be applied to each line as that line is processed.

    Fix: Place line.upper() in the expression used for printing inside the for loop.

  • Assuming the loop reads the entire file as one line

    The file object supplies one line to line on each iteration.

    Fix: Trace the value of line separately for each iteration.

  • Ignoring the newline in the current string

    A line read from the file can include a newline character.

    Fix: Use repr(line) while debugging so the exact string, including hidden newline characters, is visible.

  • Forgetting to close the file

    The file should be closed after the loop to follow the stated file-handling best practice and release the resource.

    Fix: Call file_object.close() after the loop completes.

print('Before:', repr(line)) print('After:', repr(line.upper()))

When output differs from what you expect, trace one iteration at a time. Check the value obtained from the file, the value returned by upper(), and the value sent to print. This identifies whether the problem occurs during reading, transformation, or output.

Practice the Trace

MEDIUM

Suppose a file contains the lines Data 123, I/O test!, and mixed-Case. For each loop iteration, write the value of line before upper(), the value after upper(), and the text that the program prints.

Hints
  • Keep digits, spaces, punctuation, and special characters unchanged.
  • Process one line at a time.
  • Check that the loop ends after the final line.

What do you think happens?

What does upper() do to the line stephen.marquard@uct.ac.za?

  • It changes every character, including punctuation.
  • It changes only the lowercase letters.
  • It removes the punctuation and spaces.
Reveal answer

Answer: It changes only the lowercase letters, producing STEPHEN.MARQUARD@UCT.AC.ZA.

The upper() method converts lowercase letters to uppercase while leaving punctuation, spaces, digits, and special characters unchanged.

Key Takeaways

  1. A for loop over a file object reads one line at a time and stops when all lines have been read.
  2. The loop variable contains the current line and receives a new line on each iteration.
  3. Calling line.upper() creates an uppercase version of the current line before it is printed.
  4. upper() changes letters but preserves punctuation, spaces, digits, and special characters.
  5. Close the file after the loop, and use repr() while debugging when newline characters need to be inspected.

Key Takeaways

  • A file object can be iterated with a for loop to process one line at a time.
  • The current line is transformed by calling upper() before printing.
  • The loop repeats until no lines remain, then the file should be closed.
  • Tracing the current line before and after upper() reveals where each transformation occurs.
  • repr() helps expose newline characters and other details that are not obvious in normal output.