Concepts / For Loops and Iteration

For Loops and Iteration

The loop variable is reused for each iteration, so the current value changes while the loop progresses through the file.

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

Filename promptOpen fileFor loopOne line at a timeupper()Transform current linePrint lineClose fileAfter loopfilenamefile objectcurrent lineuppercase linenext iterationno lines remain
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.

file_objectRemaining file contentslineFirst linelineSecond linelineThird lineLoop endsAll lines readread one linerepeatrepeatno lines remain
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

Definition

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.

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

Tracing Three File Lines

Worked example

Following the loop

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

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

  2. 2
    Second iteration

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

  3. 3
    Third iteration

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

  4. 4
    Completion

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

Result

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

hello worldupper() → HELLO WORLDpython rocksupper() → PYTHON ROCKSfile i/oupper() → FILE I/ONo lines remainLoop stopsnext iterationnext iterationend of file
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

  • Common mistake

    Applying upper() outside the loop

    What it looks like

    The program reads through the file with a loop but does not call upper() on the current line inside that loop.

    Why it fails

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

    Do this instead

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

  • Common mistake

    Assuming the loop reads the entire file as one line

    What it looks like

    Treating line as the complete contents of the file.

    Why it fails

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

    Do this instead

    Trace the value of line separately for each iteration.

  • Common mistake

    Ignoring the newline in the current string

    What it looks like

    Tracing hello world as though it contains only the visible letters.

    Why it fails

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

    Do this instead

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

  • Common mistake

    Forgetting to close the file

    What it looks like

    Ending the program immediately after the loop.

    Why it fails

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

    Do this instead

    Call file_object.close() after the loop completes.

Code walkthrough
print('Before:', repr(line))
print('After:', repr(line.upper()))
  1. 1
    The first statement shows the line before transformation.
  2. 2
    The second statement applies upper() and shows the returned uppercase string.
  • repr(line) displays the exact current line, including hidden newline characters.
  • repr(line.upper()) displays the transformed version of that same line.
Best practice

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

At a glance

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

Related concepts

More concepts starting with F