CIS 2020 · Python for Everyone · Module 8 · Study guide

Module 8 review: for loops, strings, and files

A for loop repeats once for each item in a collection. This guide builds that idea from counting, to loops inside loops, to processing text one character at a time, and finally to saving and loading information with files. Each example is short enough to trace by hand before you run it.

Section 4.6

The for Loop

Use a for loop when Python can visit each item for you, one at a time.

A for loop visits each item in order The word Python is a row of six characters. The loop takes one character at a time, runs the body, then moves to the next one. items P y t h o n run the loop body once for this item
A loop variable receives one item at a time. After the body runs, Python moves to the next item automatically.

Start with a list of items

The variable name after for is a temporary name for the current item. The indented lines are the loop body, and they run once per item.

pets = ["cat", "dog", "gecko"]
for pet in pets:
    print("Hello,", pet)

The output is Hello, cat, then Hello, dog, then Hello, gecko. On each pass, pet refers to a different string.

Repeat a known number of times with range()

range(stop) starts at zero and stops just before stop. That means range(4) gives 0, 1, 2, and 3: four values, not five.

for number in range(4):
    print(number)

Use two numbers when you want a different starting point. The start is included and the stop is excluded.

for number in range(3, 7):
    print(number)

This prints 3, 4, 5, and 6. A third value sets the step size.

for number in range(2, 11, 2):
    print(number)

This prints 2, 4, 6, 8, and 10. A negative step counts backward, for example range(5, 0, -1) gives 5 down to 1.

Use a loop to build a total

An accumulator is a variable that keeps a running result. Set it up before the loop, update it during each pass, and use it after the loop.

prices = [3.50, 2.00, 4.25]
total = 0

for price in prices:
    total = total + price

print("Total: $", total)

The total changes from 0, to 3.50, to 5.50, to 9.75. The loop does not need to know how many prices there are.

Trace it: Make a small table with the loop variable and any accumulator. Write one row for each pass. This is a reliable way to predict the output and find off by one errors.

Count items that match a rule

scores = [92, 68, 100, 75]
passing = 0

for score in scores:
    if score >= 70:
        passing = passing + 1

print("Passing scores:", passing)

The if runs for every score, but the counter changes only when the score is at least 70. The answer is 3.

Section 4.7

Nested Loops

A nested loop is a loop inside another loop. For every one pass of the outside loop, the inside loop completes all of its passes.

A nested loop creates a grid of row and column pairs Three rows and four columns form twelve cells. The outside loop chooses a row; the inside loop visits every column in that row. each row loop runs the full column loop row 0 row 1 row 2 0, 00, 10, 20, 3 1, 01, 11, 21, 3 2, 02, 12, 22, 3 4 columns per row 3 rows x 4 columns = 12 pairs
The inside loop goes back to its first value each time the outside loop starts a new pass.

Watch the order of the output

for row in range(1, 4):
    for column in range(1, 3):
        print("row", row, "column", column)

The output begins with row 1, column 1, then row 1, column 2. Only after both columns finish does Python move to row 2. This loop prints 3 times 2, or 6 lines.

Make a small multiplication table

for number in range(1, 4):
    for multiplier in range(1, 4):
        answer = number * multiplier
        print(number, "x", multiplier, "=", answer)
    print()

The empty print() is outside the inner loop but inside the outer loop. It adds a blank line after each number's row of answers.

Draw a pattern with repeated characters

for row in range(1, 5):
    for column in range(row):
        print("*", end="")
    print()

Here the inner loop's number of repeats changes with row. The result is a triangle with one star on the first line, two on the second, and so on. end="" keeps the stars on one line; the outside print() moves to the next line.

Common mistake: Indentation decides which loop controls a line. If a line is indented under the inner loop, it runs every inner pass. If it is indented under only the outside loop, it runs once per outside pass.

Count the work before you run it

If the outside loop runs 3 times and the inside loop runs 4 times each time, the inner body runs 12 times. To estimate the total, multiply the pass counts. If the inside loop depends on the outside loop, trace each row separately instead.

Section 4.8

Processing Strings

A string is a sequence of characters. A for loop can visit each character directly, without needing a numeric index.

Characters and indexes in the word hello The string hello has five characters with indexes zero through four. The length is five, but the last index is four. string: "hello" indexindex indexindex index 01234 hello len("hello") is 5, and the last index is 4
String indexes start at zero. The length tells you how many characters there are, not the last index.

Visit every character

word = "Python"
for letter in word:
    print(letter)

This prints one character per line: P, y, t, h, o, n. Use a character loop when you care about the characters themselves.

Use an index when position matters

word = "Python"
for index in range(len(word)):
    print(index, word[index])

len(word) is 6, so range(len(word)) produces the indexes 0 through 5. The expression word[index] gets the character at that position.

Count characters that match

message = "banana"
count = 0

for letter in message:
    if letter == "a":
        count = count + 1

print("Number of a characters:", count)

The answer is 3. The comparison is case sensitive, so uppercase "A" would not match lowercase "a".

Build a new string one character at a time

name = "sam"
shouty_name = ""

for letter in name:
    shouty_name = shouty_name + letter.upper()

print(shouty_name)

On each pass, the new uppercase character is added to the end of shouty_name. The result is SAM. String methods such as .upper() return a new string; they do not change the original string.

Check whether a character appears

email = "[email protected]"
at_signs = 0

for character in email:
    if character == "@":
        at_signs = at_signs + 1

print("At signs:", at_signs)

Loops let you inspect every character and count or transform the ones you want. For simple membership checks, Python also provides in, as in "@" in email.

Remember: The loop variable is a single character in for letter in word, but it is a number in for index in range(len(word)). Do not use the character as though it were an index.

Section 7.1

Reading and Writing Files

A file lets a program save information after it finishes. Python's open() function connects your program to a file, and a for loop can read it one line at a time, just like the loops above.

Section 7.1 now has its own page, with more than 30 short examples that show exactly what is in each file and what each program prints. It covers reading a whole file, reading line by line, reading numbers, writing and adding to files, handling a missing file, and working with CSV files.

Quick check

If you remember only these

  • A for loop visits each item in a sequence. The loop body runs once for each item.
  • range(stop) starts at 0 and stops before stop. The stop number is not included.
  • Set an accumulator to a starting value before the loop, update it inside the loop, and use it after the loop.
  • In a nested loop, the inside loop completes all of its passes for every one pass of the outside loop.
  • A string is a sequence of characters. A character loop visits characters; an index loop visits positions that start at 0.
  • len(text) is the number of characters. The final index is one less than the length.
  • Files are covered on the Section 7.1 page, which has its own quick check.