liveBook · Manning

Loop

As explained in Python Workout: 50 ten-minute exercises

A loop is a control-flow construct that repeatedly executes a block of code.

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

How Python Workout: 50 ten-minute exercises covers it

How deep it goes
Explains direct item iteration, enumerate, side effects, and alternatives through multiple exercises, but does not cover loop internals.
Examples
Uses a guessing game, Pig Latin translation, file statistics, filename creation, word lengths, and indexed alphabet output.
What it assumes
Assumes basic Python syntax while practicing input, type conversion, comparisons, strings, files, and collection operations.
What you can do after
Apply it to process iterable items, accumulate results, perform side effects, and select comprehensions for transformations.
How it connects
Connects for loops with while loops, iterables, comprehensions, enumerate, input, strings, files, dictionaries, and sets.

Also explained in

Compare how 27 books explain loop →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Workout: 50 ten-minute exercises. The section links point to the parts of the book it draws on.