Python for AIPython for AI
Control Flow

While loops

Repeat code as long as a condition is true

A while loop keeps repeating as long as a condition is True. Use it when you don't know in advance how many times to repeat: keep asking until the answer is valid, or keep chatting until the user says goodbye.

How a while loop works

python
count = 1

while count <= 3:
    print(f"Round {count}")
    count = count + 1

print("Done!")

Before every round, Python checks the condition count <= 3. If it's True, the body runs. If it's False, the loop ends and Python moves on to the next line after the loop.

count <= 3 ?
true ↓
run body, then check again
false ↓
exit loop
The condition is checked before every round.

The three parts of a while loop

  1. Set up a variable before the loop (count = 1).
  2. Check it in the condition (while count <= 3).
  3. Update it inside the body (count = count + 1), so the condition eventually becomes False.
If you forget step 3, the condition never becomes False and the loop runs forever. This is called an infinite loop. Press Ctrl + C in the terminal to stop it.

Counting with a while loop

python
countdown = 5

while countdown > 0:
    print(countdown)
    countdown -= 1      # same as countdown = countdown - 1

print("Lift off!")

Looping until something happens

This is where while really shines. The loop stops based on what happens, not on a fixed count.

python
balance = 1000
years = 0

while balance < 2000:
    balance = balance * 1.07   # 7% growth per year
    years += 1

print(f"It takes {years} years to double your money.")

Asking until the input is valid

python
password = ""

while len(password) < 8:
    password = input("Choose a password (8+ characters): ")

print("Password accepted!")

while True with break

Sometimes it's easiest to write a loop that runs "forever" and to leave it with break when you're done. This is the standard pattern for menus and chatbots.

python
while True:
    command = input("Type a command (or 'quit'): ").strip().lower()

    if command == "quit":
        print("Goodbye!")
        break

    print(f"You typed: {command}")
With while True, always double-check that there is a reachable break. See Break, continue, and pass for more ways to control loops.

Looping while a list has items

An empty list counts as False, so you can loop until a list is used up.

python
queue = ["task A", "task B", "task C"]

while queue:
    current = queue.pop(0)     # take the first item
    print(f"Working on {current}")

print("Queue empty!")

for or while?

Featurefor loopwhile loop
Best whenYou know what to loop overYou loop until a condition changes
ExampleEvery item in a listUntil the user types quit
Counter neededNo (range handles it)Yes, you update it yourself
Risk of infinite loopNoYes
Choosing the right loop.

Both loops below print 1 to 5. The for version is shorter, so prefer it when you know the count.

python
for i in range(1, 6):
    print(i)

i = 1
while i <= 5:
    print(i)
    i += 1

Common mistakes

  • Forgetting to update the variable in the condition, which creates an infinite loop.
  • Updating it in the wrong direction (for example count += 1 when the condition is count > 0).
  • Using = instead of == in the condition: while answer = "yes" is a syntax error.
  • Forgetting to set up the variable before the loop, which raises a NameError.

What's next?

Now learn how to stop a loop early, skip a round, or leave a placeholder with break, continue, and pass.