liveBook · Manning

Loop

As explained in Python Workout, Second Edition

A for loop is a control-flow construct that repeatedly executes a block while iterating over items in an iterable.

A for loop repeatedly executes a block while retrieving items directly from an iterable. Strings yield characters, dictionaries yield keys, and files yield lines, so an explicit index is usually unnecessary. section 2.15 section 11.2

Python’s loop asks the object for an iterator with iter, requests values with next, and stops when the iterator raises StopIteration. This explains why different iterable objects produce different kinds of items. section 11.2

Choose the loop form according to the task:

  • Iterate directly when the block performs an action for every item and ignores a return value, such as creating and writing one file per filename. section 8.2
  • Use enumerate when each iteration needs both an item and its numeric position; unpack its two-element tuples into separate variables. section 2.15
  • Prefer a comprehension when the goal is to transform an iterable into a new list, such as converting words into their lengths. section 8.2

Index items without manual indexing

for index, one_letter in enumerate('abcd'): print(f'{index}: {one_letter}') section 2.15

Practice with repeated input

A number-guessing game repeatedly asks for a guess, reports “Too high,” “Too low,” or “Just right,” and exits only after the correct number is entered. Related practice includes translating each word in a sentence and joining transformed output. section 2.2 section 3.6

How Python Workout, Second Edition covers it

How deep it goes
Descends from direct iteration and loop choice to iter, next, __iter__, __next__, and StopIteration, without covering broader control-flow syntax.
Examples
Demonstrates indexed alphabet output, number guessing, Pig Latin translation, file creation, and comma-joined numeric output.
What it assumes
Assumes basic Python functions, variables, strings, input, and types while developing iterable and iterator behavior through examples.
What you can do after
Build it from scratch by iterating over sequences, unpacking enumerate results, selecting comprehensions, and implementing repeated-input exercises.
How it connects
Connects for loops with iterables, iterators, enumerate, comprehensions, strings, dictionaries, files, and while loops.

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, Second Edition. The section links point to the parts of the book it draws on.