A Python for loop runs a block once for each item in an iterable. Unlike C-style loops, it retrieves items directly rather than requiring an index, making it useful for strings, files, database records, XML elements, and search results. section 1.2 section 1.18
Choose between a traditional loop and a comprehension by identifying the intended result:
- Use a traditional for loop when the goal is to execute commands or produce side effects, such as creating and writing files. section 7.1
- Use a list comprehension when transforming an iterable into a new list, such as collecting word lengths. section 7.1
- Use a dict comprehension when producing key-value pairs from an iterable, including dictionary keys and values. section 7.22
Process a file once
A loop can process each line once while accumulating several measurements: `counts = {'lines': 0, 'characters': 0, 'words': 0}`; for each `one_line` in the file, increment the line count, add `len(one_line)` to the character count, and add the length of `one_line.split()` to the word count. A set can track unique words. section 5.12
Interactive guessing game
A guessing game combines a loop with input and comparison: choose a random integer from 0 through 100, repeatedly ask for a guess, report “Too high,” “Too low,” or “Just right,” and stop only after the correct guess. section 1.2
for index, one_letter in enumerate('abcd'):
print(f'{index}: {one_letter}')
Use enumerate when iteration needs both each item and its numeric position: `for index, one_letter in enumerate('abcd'):`. section 1.18


























