← Back to Python Course | Chapter 3: Control Flow | Lesson 5 of 10

Python while Loop

Simple While Loop

A while loop re-checks its condition before every pass and keeps running its body as long as that condition stays True; the moment it evaluates to False, the loop exits and execution continues after it.

Example: Simple While Loop

python
count = 0
while count < 3:
    print(count)
    count += 1

Decrementing Loops

Subtracting from the loop variable each iteration lets a while loop count downward — a common pattern for countdowns, retry limits, or processing a shrinking range of values until it reaches zero.

Example: Decrementing Loops

python
countdown = 3
while countdown > 0:
    print(countdown)
    countdown -= 1

Using Flags for Loop Control

Using a boolean variable as the loop condition — while running: — lets code anywhere inside the loop body set that flag to False to end the loop, which is more flexible than a fixed numeric condition when the stop point depends on runtime logic.

Example: Using Flags for Loop Control

python
running = True
while running:
    print("Running")
    running = False

While Loop with Lists

A while loop paired with .pop() is a common way to drain a list one item at a time, since the list shrinks with each iteration and the loop naturally ends once it's empty.

Example: While Loop with Lists

python
items = [1, 2, 3]
while items:
    print(items.pop())

Mathematical Loops

Multiplying or dividing the loop variable each pass (rather than adding or subtracting a fixed amount) produces exponential growth or decay, useful for simulations or algorithms like binary search that repeatedly halve a range.

Example: Mathematical Loops

python
value = 1
while value < 100:
    print(value)
    value *= 2

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.