Index Ai Academy
Phase 0 · ToolsPython core

Loops

About 25 minLooking ahead: some prerequisites aren't done yet

Why this matters

AI work is repetitive in exactly the way computers are good at. Score 500 headlines. Send 20 prompts and compare the answers. Process every row of an export. Run a test over a whole set of examples. When you train a neural network in Phase 4, the training itself is a loop that runs thousands of times. Loops let you say "do this for each one" once, instead of copying code.

  • Repeat code for every item in a list with a for loop
  • Use the accumulator pattern to total, count and track the best item
  • Filter items into a new list with if inside a loop
  • Use range, enumerate, zip, while, break and continue

Do something for every item

Think of stuffing envelopes for a mailing: take the next letter, fold it, put it in, seal it, repeat until the pile is gone. A for loop is that. It runs a block of code once for each item in a list:

channels = ["search", "display", "email"]

for channel in channels:
    print("Checking", channel)

print("Done")

Read it as "for each channel in channels, do the indented block". Each pass through the loop is called an iteration. On each one, the variable channel holds the next item. You choose its name: pick the singular of the list's name, so the code reads naturally.

The block follows the same indenting rules as if. The unindented print("Done") runs once, after the loop finishes.

A loop works on a string too, one character at a time.