CIS 2020 · Python for Everyone · Module 8 · Study guide
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
for LoopUse a for loop when Python can visit each item for you, one at a time.
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.
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.
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.
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
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.
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.
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.
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.
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
A string is a sequence of characters. A for loop can visit each character directly, without needing a numeric index.
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.
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.
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".
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.
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
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.
Continue with Section 7.1: Reading and writing files, and working with CSV files.
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.len(text) is the number of characters. The final index is one less than the length.