while

In Python, the while keyword defines a loop that executes a block of code as long as a specified condition remains true.

It’s a fundamental tool for performing repeated actions in your programs. The while loop relies on a condition to control the loop execution. This makes it particularly useful when you don’t know beforehand how many iterations you need.

Python while Keyword Examples

Here’s an example of how you can use the while keyword in Python:

Python
>>> count = 0
>>> while count < 5:
...     print("Counting:", count)
...     count += 1
...
Counting: 0
Counting: 1
Counting: 2
Counting: 3
Counting: 4

In this example, the while loop executes the block of code that prints the current count and increments it by 1, as long as count is less than 5. Once count reaches 5, the condition count < 5 becomes false, and the loop terminates.

Tutorial

Python "while" Loops (Indefinite Iteration)

In this tutorial, you'll learn about indefinite iteration using the Python while loop. You’ll be able to construct basic and complex while loops, interrupt loop execution with break and continue, use the else clause with a while loop, and deal with infinite loops.

basics python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Jan. 6, 2025 • Reviewed by Dan Bader