📚 Reference guide

Loops with for and while

Use a for loop, a while loop, and range() to walk a short list of sample log file names.

Series: Python for small scripts

Based on the official Python documentation. Date checked: November 27, 2026. Script tested on Python 3.13.5.

Series: Python for small scripts, Part 4 of 10. Previous: Part 3: Decisions with if, elif, and else. Next: Part 5: Lists: Store and Filter a Set of Items.

TL;DR

Before you start

The finished script

Save this as loop.py in that folder:

names = ["app.log", "auth.log", "cron.log"]

for name in names:
    print("Checking", name)

index = 0
while index < len(names):
    print(index, names[index])
    index += 1

for number in range(3):
    print("range:", number)

When you run it, you should see:

Checking app.log
Checking auth.log
Checking cron.log
0 app.log
1 auth.log
2 cron.log
range: 0
range: 1
range: 2

Steps

  1. Save and run the script. Change into python-scripts and run python3 loop.py. Why: you can see all three styles of loop in one output. You should see: the nine lines above.
  2. Read the for loop. names is a list of three sample file names. for name in names: sets name to each item in turn and runs the indented print line. Why: you can process every item without writing print three times.
  3. Read the while loop. len(names) is 3. The loop starts at index = 0 and continues while index is less than 3. index += 1 adds one after each print, so the condition later becomes false. Why: while is useful when you stop on a condition, but you must change that condition inside the loop or it never ends.
  4. Read the range(3) loop. range(3) produces 0, 1, and 2. It does not include 3. Why: range is the usual way to walk a sequence of numbers. You should see: range: 0, then 1, then 2.

If it fails

Stay safe

Next

Part 5: Lists: Store and Filter a Set of Items

Sources

Spot something wrong or outdated? Leave a comment below. Every comment is reviewed to keep these posts accurate.

By commenting, you agree to our Terms of use and confirm this is your own work. Short quotes are fine with a credit and link. Copied, unsafe, or abusive comments are removed. See something copied? Say so here.