Search⌘ K
AI Features

While Loops and Counters

Explore how to use while loops to repeat code execution based on conditions in Python. Understand how to implement counters to control iterations, prevent infinite loops by updating variables properly, and use sentinel values to manage loop termination. This lesson prepares you to write dynamic, responsive programs that automate repeated actions until specific conditions are met.

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 ...