New: 6 free SQL practice datasets with 300+ questions — try the SQL Compiler →
Python

Python Loops: for, while, break and continue

Python loops explained: for, while, range, enumerate, break, continue and loop else, with real code and output, common mistakes and practice questions.

Upskly AI Team September 26, 2026 8 min read
Python Loops: for, while, break and continue

Python loops repeat a block of code. A for loop goes through the items of a sequence one by one, so you use it when you know what to loop over. A while loop keeps going as long as a condition is true, so you use it when you do not know in advance how many rounds you need. Inside either loop, break stops the loop and continue skips to the next round.

Below is each loop type with real output, plus the patterns and mistakes that matter in practice.

In this guide

The short version

  • for item in collection: – run once per item.
  • for i in range(n): – run n times, with i counting 0 to n-1.
  • while condition: – repeat until the condition becomes false. Make sure something changes it.
  • break leaves the loop. continue skips to the next round.

The for loop

A for loop takes each item from something you can iterate over (a list, a string, a dictionary, a range) and runs the indented block once for each. The loop variable, lang here, holds the current item:

languages = ["SQL", "Python", "Excel"]
for lang in languages:
    print(lang)
for ch in "Hi":
    print(ch)

Output

SQL
Python
Excel
H
i

Indentation is how Python knows which lines belong to the loop. Everything indented under the for line runs on every round.

Looping a set number of times with range()

range() produces a sequence of numbers. It takes up to three arguments: range(stop), range(start, stop) and range(start, stop, step). Like slicing, the stop value is never included:

print(list(range(5)))
print(list(range(2, 8)))
print(list(range(10, 0, -3)))
for i in range(3):
    print("Round", i + 1)

Output

[0, 1, 2, 3, 4]
[2, 3, 4, 5, 6, 7]
[10, 7, 4, 1]
Round 1
Round 2
Round 3

range(5) gives 0, 1, 2, 3, 4: five numbers, starting from zero. A negative step counts down.

Getting the index: enumerate() and zip()

If you need the position as well as the item, do not build the counter yourself. Use enumerate(). To walk through two lists together, use zip():

names = ["Asha", "Ravi", "Meera"]
marks = [90, 72, 85]
for i, name in enumerate(names, start=1):
    print(i, name)
for name, mark in zip(names, marks):
    print(name, mark)

Output

1 Asha
2 Ravi
3 Meera
Asha 90
Ravi 72
Meera 85

enumerate(names, start=1) counts from 1 instead of 0, which is handy for numbered lists. zip() stops at the shorter list.

The while loop

A while loop checks its condition before every round and stops when it is false. The code inside must eventually change something that affects the condition:

count = 3
while count > 0:
    print("T-minus", count)
    count -= 1
print("Liftoff")

Output

T-minus 3
T-minus 2
T-minus 1
Liftoff

Use while for things like “keep asking until the input is valid”, “keep going until the balance runs out”, or digit-by-digit maths. When you are simply going through a collection, a for loop is clearer and safer.

break and continue

break ends the loop immediately. continue abandons the current round and jumps to the next one. In this loop, even numbers are skipped, and the loop stops once the number goes above 7:

for n in range(1, 10):
    if n % 2 == 0:
        continue
    if n > 7:
        break
    print(n)

Output

1
3
5
7

The loop else clause

Python lets a loop have an else block. It runs only if the loop finished normally, meaning it was not ended by break. That makes it perfect for “search and report if not found”:

numbers = [4, 8, 15, 16]
for n in numbers:
    if n == 23:
        print("found")
        break
else:
    print("23 is not in the list")

Output

23 is not in the list

If 23 had been in the list, the loop would have printed “found”, hit break, and skipped the else.

Nested loops

A loop inside a loop runs the inner loop completely for each round of the outer one. Here is a small multiplication table (the end="" keeps each row on one line):

for i in range(1, 4):
    for j in range(1, 4):
        print(f"{i * j:3}", end="")
    print()

Output

  1  2  3
  2  4  6
  3  6  9

Nested loops multiply the work: 3 by 3 gives 9 rounds, and 1,000 by 1,000 gives a million. Keep that in mind when a program feels slow.

Three loop patterns to know

Most loops you write are one of these: adding things up, finding the biggest, or picking out items that match a condition.

prices = [120, 80, 250, 40]
total = 0
for p in prices:
    total += p
print(total)
biggest = prices[0]
for p in prices:
    if p > biggest:
        biggest = p
print(biggest)
cheap = []
for p in prices:
    if p < 100:
        cheap.append(p)
print(cheap)

Output

490
250
[80, 40]

Python has built-ins for the first two, so in real code you would write this:

prices = [120, 80, 250, 40]
print(sum(prices), max(prices), min(prices))
print(list(reversed(range(1, 4))))

Output

490 250 40
[3, 2, 1]

Writing the loop by hand is still worth practising, because the same shape (start with a value, update it as you go) appears everywhere. The third pattern, building a filtered list, becomes a one-liner with a list comprehension, which we cover in Python List Comprehension Explained Simply.

Common mistakes

Mistake 1: an infinite loop

If nothing inside a while loop changes the condition, the loop never ends. This is what it looks like (do not run it):

count = 3
while count > 0:
    print("T-minus", count)
    # forgot count -= 1, so this never stops

Add count -= 1 and it works. If you ever start one by accident, stop it with Ctrl+C.

Mistake 2: forgetting that range() excludes the stop value

To include the last number, add 1 to the stop value:

print(list(range(1, 5)))
print(list(range(1, 5 + 1)))

Output

[1, 2, 3, 4]
[1, 2, 3, 4, 5]

Mistake 3: removing items from a list while looping over it

When you remove an item, everything after it shifts left, and the loop skips the next one. We wanted to remove every even number, but half of them survive:

nums = [2, 4, 6, 8]
for n in nums:
    if n % 2 == 0:
        nums.remove(n)
print(nums)

Output

[4, 8]

Loop over a copy (list(nums)), or better, build a new list:

nums = [2, 4, 6, 8]
for n in list(nums):
    if n % 2 == 0:
        nums.remove(n)
print(nums)
nums = [1, 2, 3, 4, 5, 6]
nums = [n for n in nums if n % 2 != 0]
print(nums)

Output

[]
[1, 3, 5]

Mistake 4: assuming the loop variable disappears

In Python the loop variable stays alive after the loop and keeps its last value:

for i in range(3):
    pass
print(i)

Output

2

Try it yourself

Work out each answer first, then open the solution.

1. Produce the even numbers from 2 to 10.

Show solution
print(list(range(2, 11, 2)))

Output

[2, 4, 6, 8, 10]

The step of 2 does the work, and the stop value 11 is needed so that 10 is included.

2. Add up the digits of 4821 using a while loop.

Show solution
n, total = 4821, 0
while n > 0:
    total += n % 10
    n //= 10
print(total)

Output

15

n % 10 gives the last digit, and n //= 10 removes it.

3. Print the numbers 1 to 10, skipping multiples of 3 and stopping once you pass 8.

Show solution
for n in range(1, 11):
    if n % 3 == 0:
        continue
    if n > 8:
        break
    print(n, end=" ")

Output

1 2 4 5 7 8 

continue skips 3, 6 and 9 (9 is skipped before the break check runs), and break ends the loop at 10.

Run these in our free Python compiler and change the numbers.

Frequently asked questions

What is the difference between a for loop and a while loop?

A for loop goes through a known collection or a fixed number of rounds. A while loop repeats until a condition becomes false, which is useful when you do not know the number of rounds in advance.

How do I loop a specific number of times in Python?

Use for i in range(n):. It runs n times, with i taking the values 0 to n-1. If you do not need the counter, name it _.

How do I get the index while looping?

Use for i, item in enumerate(items):. Add start=1 if you want the counting to begin at 1.

What is the difference between break and continue?

break exits the whole loop. continue only skips the rest of the current round and moves on to the next one.

What does else do on a loop?

The else block runs when the loop ends normally, without hitting break. It is useful for searches: found it, break; otherwise the else reports that nothing was found.

How do I loop backwards?

Use reversed(items) for a list or a range, or range(start, stop, -1) with a negative step.

Run this code in your browser

The free Upskly compiler runs Python with nothing to install. Paste the example, change it and see what happens.

Open Python Compiler

Stuck on a traceback?

AI Assist works inside the Python notebook, so you can ask about an error or a concept without leaving the cell.

Try AI Assist

Test yourself

Timed questions on Control Flow and Comprehensions, with an explanation for every answer.

Take the Quiz
Upskly AI Team
Learning made simple
Scroll to Top