A for loop runs a block once for each value produced by a sequence or iterable. In Python, strings provide characters, lists provide elements, and open files provide lines. Each pass assigns the next value to a loop variable. section 4.6 section 6.1.2
Visit every character
A small text-processing task can inspect and transform one character at a time: text = 'ABC123' for char in text: print(char) This prints A, B, C, 1, 2, and 3 on separate lines. A dictionary can supply replacements while dict.get(char, char) preserves characters without a matching key: new_text = '' for char in text: new_text += jumper.get(char, char) print(new_text) For the Jump the Five table, the result is ABC987. Use print(..., end='') when each iteration should continue on the same output line. section 4.2 section 4.4.3
Choose the loop shape according to what each iteration must accomplish:
- Perform an action, such as printing each value or handling each input line. section 12.3.5
- Build a result by appending transformed values to a list, then combine them with ''.join(). section 12.3.1
- Replace result-building loops with a list comprehension when the goal is a new list; use map() for another equivalent form. section 8.6 section 11.5
- Use range() when the loop should repeat a known number of times, including descending ranges with a step of -1; use _ for an ignored value. section 9.1.5 section 9.3.5
Process files with nested loops
A file-counting program can loop over file handles and then over each handle's lines: for fh in args.file: lines, words, bytes = 0, 0, 0 for line in fh: lines += 1 bytes += len(line) words += len(line.split()) print(f'{lines:8}{words:8}{bytes:8} {fh.name}') The outer loop handles multiple files; the inner loop reads one line at a time instead of loading a large file into memory. After each file, totals can be updated. section 6.3.2 section 6.5
Generate repeated or descending results
Use range() to run an operation repeatedly: for _ in range(3): print('An insult!') For numbered output, keep the value instead. For descending verses, iterate over a range from the starting number toward 1 and call a verse function on each value. Tests can verify the complete output before refactoring the working loop into a comprehension or map(). section 9.3.5 section 11.1.4
>>> for char in 'ABC123': ... print(char) ... A B C 1 2 3
A short REPL listing makes the loop's sequence traversal visible by showing each character produced in order. section 4.2


























