Search⌘ K
AI Features

While Loops and Counters

Explore how to use Python while loops to repeat code based on conditions. Learn to implement counters for controlled iteration, avoid infinite loop errors, and handle user input with sentinel values for dynamic program control.

So far, we have learned how to write programs that make decisions using if statements. However, these programs still execute from top to bottom only once. To build true automation, such as programs that process large amounts of data or continue running until a user chooses to stop, we need a way to repeat actions. This repetition is called iteration.

In Python, the while loop enables iteration by repeatedly executing a block of code as long as a specified condition remains true. By using loops, we transform programs from simple, one-time instructions into continuous processes that can respond dynamically to changing data.

The structure of a while loop

A while loop works like a repeating if statement. It evaluates a boolean condition; if the condition is True, it executes the indented block of code. Once the block finishes, Python loops back to the top and rechecks the condition. This cycle continues until the condition becomes False.

The syntax relies on the while keyword followed by a condition and a ...