Python + AI/ML · Tutorial 1 of 5
Python Loops: for and while, with real examples
By the FUTEAC Team · 25 October 2026 · 9 min read · Beginner
In short
A loop repeats a block of code until a condition says stop. A for loop runs once for each item in a collection — or each number in a range — so use it when you know how many repeats you need. A while loop runs until a condition becomes false, so use it when the count is unknown.
foris for a known collection or count.for name in names:runs once per item;for n in range(1, 6):runs five times.whileis for a condition.while count > 0:keeps going untilcountreaches zero — you must change the condition inside the loop, or it never stops.- Indentation is the loop body. Every line indented under the
fororwhileline runs each time round; the first unindented line runs after the loop finishes. breakstops the loop;continueskips one round. Both are for control flow, not for everyday use — a clear condition is usually better.- This tutorial feeds the Python Programming Foundations course (/course/python-programming-foundations) and the Python Programming skill (/skill/python).
Before you start
Why do you need a loop at all?
Imagine five students and you want to greet each one. Without a loop you write the same line five times:
print("Hello, Ayesha")
print("Hello, Bilal")
print("Hello, Chen")That works for three names and breaks down for three hundred. A loop says "do this once for each item" instead of "do this, do this, do this":
names = ["Ayesha", "Bilal", "Chen"]
for name in names:
print("Hello,", name)Output, verified by running it:
Hello, Ayesha
Hello, Bilal
Hello, ChenThe loop variable name takes a different value each time round — first "Ayesha", then "Bilal", then "Chen" — and the loop stops by itself when the list runs out. That is the whole point of a loop: one block of code, as many repetitions as the data needs.
How does a `for` loop work?
A for loop has three parts:
names = ["Ayesha", "Bilal", "Chen"]
for name in names:
print("Hello,", name)for— the keyword that starts the loop.- The loop variable (
name) — a new variable that holds the current item. You choose its name; a clear name makes the loop readable. - The collection (
names) — anything with items: a list, a string, or the result ofrange().
Everything indented underneath is the loop body. Python uses the indentation, not brackets, to know which lines belong to the loop. The loop runs the body once per item, in order, then continues with the first line that is not indented.
A for loop also works over a string — each character in turn:
for letter in "loop":
print(letter)Output:
l
o
o
pWhat is `range()` — and why does it stop one short?
When you need to repeat a fixed number of times rather than over a list, use range():
for number in range(1, 6):
print(number)Output:
1
2
3
4
5range(1, 6) produces 1, 2, 3, 4, 5 — it stops *before* the second number. This catches every beginner out once. The reason is consistency: range(5) produces 0, 1, 2, 3, 4 — exactly five numbers, starting from zero. So range(n) always gives you n items, and range(start, stop) gives you stop - start items. If you want 1 to 10, write range(1, 11).
range() also takes a step: range(0, 11, 2) produces 0, 2, 4, 6, 8, 10.
How does a `while` loop work?
A while loop repeats *while a condition is true*, and you do not need to know in advance how many times that will be:
count = 3
while count > 0:
print(count)
count = count - 1
print("Go!")Output:
3
2
1
Go!The condition count > 0 is checked before every round, including the first. If it is false at the start, the body never runs at all. The line count = count - 1 is doing the essential work: it moves the condition toward false. Forget that line and the loop runs forever — Python will keep printing 3 until you stop it with Ctrl+C.
Use while when the number of repeats depends on something that happens during the loop — waiting for valid input, reading lines until a file ends, or retrying until a condition is met. Use for when you already have the items or the count. If you find yourself writing a while with a counter that goes up by one each time, you almost certainly wanted for number in range(...).
The worked example: a week of expenses, totalled by a loop
Here is the pattern loops exist for: a list of numbers, one pass, three answers. A week's expenses in rupees:
expenses = [1200, 450, 800, 1500, 300, 950, 600]
total = 0
over_1000 = 0
for amount in expenses:
total = total + amount
if amount > 1000:
over_1000 = over_1000 + 1
average = total / len(expenses)
print("Total spent:", total)
print("Daily average:", round(average, 1))
print("Days over 1000:", over_1000)Output, exactly as printed when run:
Total spent: 5800
Daily average: 828.6
Days over 1000: 2Trace it mentally, one round at a time, and the output is inevitable:
totalstarts at 0. Each round adds one day's expense: 0 → 1200 → 1650 → 2450 → 3950 → 4250 → 5200 → 5800.over_1000only increases when the day's amount is above 1000 — that happens for 1500 and 1200, so it ends at 2.len(expenses)is 7, soaverageis 5800 / 7 = 828.571…, rounded to 828.6.
Two details worth noticing. First, the if inside the loop is indented *further* than the loop body — it is a block inside a block, and indentation is what makes that structure visible. Second, total = total + amount is the accumulator pattern: start at zero, add each item, and the variable holds the running total. You will use this pattern in almost every program that summarises data — and it is the same idea behind the spreadsheet formulas in the data cluster's Excel formulas tutorial.
What about `break` and `continue`?
Sometimes a loop needs an early exit or a skipped round:
for number in range(1, 11):
if number == 3:
continue
if number == 8:
break
print(number)Output:
1
2
4
5
6
7continueskips the rest of this round and jumps to the next one — so 3 never prints.breakstops the loop entirely — so 8, 9 and 10 never print.
Both are useful sparingly. A loop full of break and continue is hard to read; if you are using them to express the loop's real condition, rewrite the condition instead. The cleanest use of break is searching: loop through items, break the moment you find the one you want.
Try it yourself
Write a program that asks for five numbers (use a list you type in, like the expenses example), then prints the largest one and how many of the five are above 100. Start with largest = 0 before the loop and update it inside the loop with an if. When it works, test yourself in the Module Quiz: Flow and Collections on the Python Programming Foundations course page (/course/python-programming-foundations).
Continue in the free course: Python Programming Foundations →
Common mistakes
- Forgetting to change the
whilecondition. Awhileloop whose condition never becomes false runs forever. Check that something inside the body moves the condition toward false — usually a counter going down or a value being updated. - Wrong indentation. A line indented one space too few is outside the loop; one space too many is a different block. In the expenses example, if
total = total + amountwere not indented, it would run once, after the loop, andtotalwould be just the last amount (600). - Off-by-one with
range().range(1, 5)gives 1, 2, 3, 4 — not 5. If your loop is one short, the stop value is almost always the cause. - Reusing the loop variable after the loop. After
for name in names:finishes,namestill holds the *last* item ("Chen"). Do not rely on it after the loop — it is leftover state, not a result. - Modifying a list while looping over it. Removing items from a list inside a
forover that same list skips items, because the loop's position and the list's contents move out of sync. Loop over a copy (for item in names[:]:) if you must remove items.
Frequently asked questions
When should I use for and when while?
Use for when you have the items or the count before the loop starts — a list, a string, or range(). Use while when the number of repeats depends on something that happens inside the loop, like waiting for valid input. If your while is just counting up to a known number, rewrite it as a for with range().
Why does range(1, 6) not include 6?
range() stops before its second argument, so range(start, stop) always produces exactly stop - start numbers. It is the same rule in every language that uses half-open ranges, and it means range(5) gives five items starting from zero. If you want 1 to 10, write range(1, 11).
Can a loop contain another loop?
Yes — a nested loop. The inner loop runs completely for each round of the outer loop, so for row in range(3): with for col in range(3): inside it runs the inner body nine times. Keep nesting shallow; two levels is normal, three is a sign to split the code into a function.
What is the difference between break and continue?
break exits the loop completely and continues with the code after it. continue skips only the current round and starts the next one. Both work in for and while loops, and both only affect the innermost loop they sit in.
My loop runs but produces the wrong total — where do I look?
Check three things in order: is the accumulator (total = 0) set *before* the loop, not inside it (inside would reset it every round)? Is the adding line indented inside the loop body? And is the final print outside the loop — indented inside, it prints a running total every round instead of the final answer. ---
Follow the Python + AI/ML Beginner Roadmap
Learn Python from zero and take your first steps into AI and machine learning. Free, step by step, at your pace.
View the Roadmap