Thuta Learning
Python
BasicProgrammingBeginner

Python Loops: for, while, break and continue

PythonLesson 1830 min

What you'll walk away with

  • Decide when a for loop fits and when a while loop fits
  • Use range(start, stop, step), knowing stop is excluded, plus enumerate() and zip()
  • Explain break versus continue and predict when a loop's else block runs
  • Avoid infinite loops and the bug of changing a list while looping over it

Explain it simply

Explain it simply

Picture a teacher marking exam papers. She takes the papers from the pile one at a time, grades each one, and stops when the pile is empty. That is a for loop: handle each item in a collection, then stop when there are no more.

A while loop is more like scooping ice from a tray while there is ice left. You do not know in advance how many times you will repeat; you recheck "is the condition still true?" every time. break means "stop right here", and continue means "skip this one and move on to the next".

Problem → Why → Solution

The problem: deleting from a list while looping over it

One developer wants to drop every score below 50, so he calls remove() inside a for loop over the same list. There is no error, yet 45 survives in the result. Another developer writes a retry loop, forgets to decrease the counter, and the program never stops while it pins the CPU at full load.

loop_bugs.py
scores = [40, 45, 90, 30]
for s in scores:
    if s < 50:
        scores.remove(s)   # shifts the remaining items left
print(scores)  # [45, 90] -- 45 was skipped, never checked

attempts = 3
while attempts > 0:
    print("trying...")
    # forgot: attempts -= 1  -> runs forever

Why does this happen?

A for loop reads a list by index: 0, 1, 2 and so on. Removing 40 moves 45 into index 0, but the loop moves on to index 1, which is now 90, so 45 is never examined. A while loop never stops if nothing in its body can make the condition False. The fixes are to build a new list instead, and to make sure every while loop has a guaranteed way to end.

Core concept: for consumes an iterable, while tests a condition

for item in iterable: takes one item at a time from any iterable, such as a list, tuple, string, set, dict or range, assigns it to the variable and runs the body. The loop stops on its own when the items run out, so you never manage a counter by hand. Looping over a string gives one character at a time, and looping over a dict gives its keys. Reassigning the loop variable inside the body does not change the list, and after the loop ends the variable still holds the last item.

When you want to repeat a fixed number of times, use range(). range(5) yields 0 to 4, and range(2, 11, 3) yields 2, 5 and 8: the stop value is never included. When you need the index and the value together, use enumerate(items, start=1) rather than range(len(items)), and to walk two lists side by side use zip(names, marks), which stops when the shorter list runs out.

while condition: checks the condition before every pass and stops as soon as it is False. It suits situations where the number of passes is unknown in advance, such as asking until the user types something valid or compounding interest until a target is reached. The body must always contain a change that eventually makes the condition False.

break leaves the nearest loop immediately, while continue skips the rest of the current pass and moves to the next item. Python loops also accept an else clause, which runs only when the loop finishes normally without hitting break. That lets you write the "search, break when found, else report not found" pattern without a flag variable.

Mental model: for stops when empty, while stops when false
  1. for: fetch the next item
  2. Run the body (continue skips ahead)
  3. Stop when empty or on break
  4. while: test the condition first

A loop's else means "no break happened", not "always run when the loop is over".

General pattern

python
for item in iterable:
    if skip_condition:
        continue
    if stop_condition:
        break
    process(item)
else:
    no_break_happened()

while condition:
    do_work()
    update_something_the_condition_uses()

Inside the for loop, continue skips an item and break leaves the loop entirely; else runs only if no break happened. The last line of the while loop is the step that changes the condition; without it you get an infinite loop.

Example: passing scores and remaining attempts

The first loop walks the score list with enumerate(), skips anything below 50 with continue, and prints the rest with their position. The second loop counts down with while until no attempts are left.

python
scores = [68, 42, 91, 77]

for index, score in enumerate(scores, start=1):
    if score < 50:
        continue
    print(f"{index}: {score}")

attempts = 3
while attempts > 0:
    print(f"Attempts left: {attempts}")
    attempts -= 1

Code breakdown

  1. Line 3for index, score in enumerate(scores, start=1):

    enumerate() yields (number, value) pairs, and start=1 makes the numbering begin at 1. The loop unpacks each pair into index and score.

  2. Lines 4-5 continue

    42 is below 50, so continue skips the print and jumps to the next score. That is why the output shows 1, 3 and 4 but not 2.

  3. Line 9while attempts > 0:

    The condition is checked before every pass: True for 3, 2 and 1, then False at 0, which ends the loop.

  4. Line 11 attempts -= 1

    This line is the change that eventually makes the condition False. Delete it and "Attempts left: 3" prints forever.

You should see
1: 68
3: 91
4: 77
Attempts left: 3
Attempts left: 2
Attempts left: 1

range, zip and the loop else

The code below shows the step argument of range(), walking two lists together with zip(), and else on a search loop. Nobody scored the target of 50, so break never runs and the else block prints "nobody scored 50". Change target to 47 and you get found Bo, with no else output.

range_zip_else.py
for n in range(2, 11, 3):
    print("range gives", n)

names = ["Aye", "Bo", "Chit"]
marks = [81, 47, 66]
for name, mark in zip(names, marks):
    print(f"{name}: {mark}")

target = 50
for name, mark in zip(names, marks):
    if mark == target:
        print("found", name)
        break
else:
    print("nobody scored", target)

In real projects

Where this shows up in real projects

A script that imports rows from a CSV file uses a for loop to read each row, putting good rows in a valid list and bad rows, together with the row number from enumerate(), in an errors list. That is how it can tell the user something precise like "row 17 has an invalid email". It should also be tested with an empty file, where the loop body never runs at all.

Code that retries a network request uses a while loop, but production versions always include a maximum number of attempts, a growing wait between tries (backoff) and a timeout, because an endless retry loop makes a struggling server worse. Game loops and workers that pull messages from a queue are while loops too, and they leave with break when a shutdown signal arrives.

Common mistakes

Common mistakes

1. Changing the list you are iterating

As the problem section showed, calling remove() inside the loop skips items. Create passing = [] first and append() only the items you want to keep, or iterate over a copy with for s in scores[:].

2. A while loop that never changes its condition

Forgetting to decrease a counter, or reading input once outside the loop, creates an infinite loop. For every while loop you write, you should be able to point at the line that eventually makes the condition False. Press Ctrl+C to stop a runaway loop in the terminal.

3. Expecting range() to include stop

range(1, 10) yields 1 to 9 only; to include 10 write range(1, 11). Off-by-one errors are the most common loop bug of all.

4. Misreading the loop else

A loop's else does not run every time the loop ends; it runs only when no break happened. If you indent else to match an if inside the body by mistake, "not found" prints for every item, so align the else with the for keyword.

Best practices

Best practices

  • Loop over the items directly; reach for range(len(items)) only when you truly need the index.
  • Collecting results in a new list is safer than editing an existing list inside the loop.
  • Give every while loop a maximum number of passes, especially for network calls and user input.

Mini challenge

Mini challenge: clean up an order list

Loop over quantity strings typed by users: add up the valid ones, record the positions of invalid ones, and stop at "STOP". Then use a while loop to find how many months savings need to reach 150.

  • Get positions with enumerate(entries, start=1)
  • On "STOP", print its position and break (the "9" after it must not be added)
  • For an entry that is not isdigit(), add its position to bad and continue
  • If no STOP is found, the loop's else prints "no stop marker found"
  • Count with while how many months 100 growing 10% a month needs to reach 150
orders.py
entries = ["3", "x", "5", "-2", "4", "STOP", "9"]

total = 0
bad = []
# TODO: for position, text in enumerate(...):
#   STOP -> print the position and break
#   not text.isdigit() -> remember the position, continue
#   otherwise add int(text) to total
# TODO: loop else -> print "no stop marker found"

# TODO: print total and bad

balance = 100
months = 0
# TODO: while balance is below 150, grow it by 10% and count the month
# TODO: print months and the rounded balance

Expected: stop marker at 6 total: 12 bad entries at: [2, 4] 5 months -> 161.05

Show hint

"-2".isdigit() is False, so negative numbers also count as invalid. Align the else with the for, not with an if. Print the balance with round(balance, 2).

Show solution
orders.py
entries = ["3", "x", "5", "-2", "4", "STOP", "9"]

total = 0
bad = []
for position, text in enumerate(entries, start=1):
    if text == "STOP":
        print("stop marker at", position)
        break
    if not text.isdigit():
        bad.append(position)
        continue
    total += int(text)
else:
    print("no stop marker found")

print("total:", total)
print("bad entries at:", bad)

balance = 100
months = 0
while balance < 150:
    balance = balance * 1.1
    months += 1
print(months, "months ->", round(balance, 2))

Quick quiz 1 / 3

What does for n in range(1, 10, 3): print(n) print?

Quick quiz 2 / 3

for x in [1, 2, 3]: if x == 5: break, followed by else: print("done"). What happens?

Quick quiz 3 / 3

When you need both the index and the value, which form is the most Pythonic?

What to remember

  • for takes items from an iterable until they run out; while runs until its condition is False.
  • range() excludes stop, enumerate() adds an index, and zip() pairs two lists.
  • break leaves the loop, continue skips the current pass, and else runs only without a break.
  • Never edit the list you are looping over, and give every while loop a guaranteed exit.

The Python Tutorial — Python Software Foundation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Python Loops: for, while, break and continue | Thuta Learning