liveBook · Manning

Infinite loop

As explained in Python Workout: 50 ten-minute exercises

A loop whose condition remains true until an explicit control-flow operation exits it.

An infinite loop keeps running because its condition remains true. In Python, while True creates this pattern; break must provide an explicit exit, usually after the desired input or result appears. section 1.3 section 4.9

Use an infinite loop when a program should continue accepting attempts until a meaningful stopping condition occurs:

  • A number-guessing program repeatedly requests guesses and breaks when the converted integer equals the randomly selected answer. section 1.3
  • A rainfall collector repeatedly reads city names and measurements, updating a dictionary until control flow exits the loop. section 4.9
  • Place validation inside the loop: invalid rainfall input prints an error and continue starts the next iteration. section 4.9

A loop that waits for a correct guess

Generate an answer with random.randint, then run while True. Convert input from its returned string form with int(...), compare the integer with answer, and use break when the guess is correct. Without that break, the loop has no exit. section 1.3

How Python Workout: 50 ten-minute exercises covers it

How deep it goes
Explains while True, break, continue, validation, and input conversion through two worked interactive programs.
Examples
Demonstrates number guessing with random.randint and rainfall collection with dictionary updates.
What it assumes
Assumes familiarity with Python input and comparisons while reinforcing string-to-integer conversion and Boolean string checks.
What you can do after
Apply it via Python to build interactive loops with explicit exits and retry paths for invalid input.
How it connects
Ties infinite loops to while loops, break statements, continue statements, Boolean conditions, input conversion, and dictionaries.

Also explained in

Compare how 3 books explain infinite 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.