Python Loops

Repeat code with for loops, while loops and range(), and control them with break and continue.

Lesson 18 of 107Beginner18 min read

Computers are brilliant at repeating things without getting bored. A loop runs the same block of code again and again: once for every item in a list, a fixed number of times, or for as long as a condition stays true.

Python has two kinds of loop. A for loop goes through a sequence of values, one at a time. A while loop keeps going while a condition is true. Between them they cover almost every kind of repetition you'll need.

In this lesson you'll loop over text and numbers with for and range(), repeat until something changes with while, and steer loops with break and continue.

for loops

A for loop takes each item from a sequence in turn and runs its indented block once per item:

Python
for letter in "cat":
    print(letter)

This prints c, a and t on separate lines. The variable after for, here letter, holds the current item on each pass. You can name it anything, but a clear name makes the loop easier to read: for name in names, for price in prices.

Counting with range()

range() produces a sequence of whole numbers, which is perfect for repeating something a set number of times:

CallNumbers produced
range(5)0, 1, 2, 3, 4
range(1, 6)1, 2, 3, 4, 5
range(0, 20, 5)0, 5, 10, 15
range(10, 0, -2)10, 8, 6, 4, 2

The end number is never included. range(1, 6) stops at 5. The optional third number is the step: how much to add each time.

Looping with enumerate() and zip()

Beginners often loop over range(len(items)) just to get a position number. Python has a cleaner tool for that: enumerate() gives you the position and the item together.

Python
songs = ["Intro", "Skyline", "Outro"]
for number, title in enumerate(songs, start=1):
    print(number, title)

This prints 1 Intro, 2 Skyline and 3 Outro. Without start=1, counting begins at 0.

zip() walks through two or more sequences side by side, pairing up items in the same position:

Python
names = ["Ada", "Linus", "Grace"]
scores = [91, 78, 85]
for name, score in zip(names, scores):
    print(f"{name}: {score}")

zip() stops when the shortest sequence runs out, so mismatched lengths don't cause an error, but extra items are silently ignored.

while loops

A while loop checks its condition before every pass and stops as soon as it's false:

Python
countdown = 3
while countdown > 0:
    print(countdown)
    countdown -= 1
print("Lift off!")

Use while when you don't know in advance how many repeats you need, for example "keep asking until the answer is valid". Something inside the loop must eventually make the condition false, or the loop never ends.

break and continue

  • break leaves the loop immediately, skipping any remaining items.
  • continue skips the rest of the current pass and jumps to the next item.
Python
for n in range(1, 10):
    if n == 6:
        break        # stop completely at 6
    if n % 2 == 0:
        continue     # skip even numbers
    print(n)

This prints 1, 3 and 5. Both keywords work in for and while loops.

Nested loops and the loop else clause

A loop inside another loop runs completely for every pass of the outer loop. Nested loops are how you work through rows and columns:

Python
for row in range(1, 4):
    for col in range(1, 4):
        print(row * col, end=" ")
    print()

This prints a 3 by 3 multiplication grid. The inner loop runs three times for each of the three outer passes, nine passes in total. break only leaves the innermost loop it is in.

Loops in Python can also have an else block. It runs when the loop finishes normally, and is skipped if the loop ends with break. That makes it a neat way to report "not found":

Python
for n in [3, 7, 11]:
    if n % 2 == 0:
        print("Found an even number:", n)
        break
else:
    print("No even numbers")

Here every number is odd, so the loop never breaks and the else block prints No even numbers.

Choosing between for and while

Use a for loop when you are working through something that already exists: a list, a string, a file or a range of numbers. Use a while loop when you are waiting for something to change: valid input, a game ending, or a balance reaching a target. If you catch yourself writing a counter, a while condition and counter += 1, a for loop over range() is usually shorter and can't run forever by mistake.

Python Loops Syntax

for and while loops

for item in sequence:
    # runs once per item

for i in range(start, stop, step):
    # i takes each number in turn

while condition:
    # runs while condition is True

Python Loops Summary

  • for item in sequence: runs once for each item.
  • range(start, stop, step) makes number sequences; stop is not included.
  • while condition: repeats as long as the condition is true.
  • Update the condition inside a while loop or it will run forever.
  • break exits the loop; continue skips to the next pass.

Python Loops Examples

Each example shows the code, the output it produces and what each part does.

Example 1

Times table

Python
number = 7

for i in range(1, 6):
    print(f"{number} x {i} = {number * i}")
Output
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
Line-by-line explanation
  1. Line 3i takes the values 1, 2, 3, 4 and 5. The stop value 6 is not included.
  2. Line 4The f-string builds one line of the table on every pass.
Example 2

Adding up with a loop

Python
total = 0

for n in range(1, 11):
    total += n

print("Sum of 1 to 10 is", total)
Output
Sum of 1 to 10 is 55
Line-by-line explanation
  1. Line 1Start a running total at zero, before the loop.
  2. Line 4Each pass adds the current number to the total.
  3. Line 6Not indented, so it runs once, after the loop has finished.
Example 3

Guess the number with while

Here the player guessed 3, then 8, then 5.

Python
secret = 5
guess = 0
tries = 0

while guess != secret:
    guess = int(input("Guess: "))
    tries += 1

print(f"Got it in {tries} tries!")
Output
Guess: 3
Guess: 8
Guess: 5
Got it in 3 tries!
Line-by-line explanation
  1. Line 5The loop keeps going until the guess matches the secret.
  2. Lines 6 to 7Each pass asks again and counts the attempt.
  3. Line 9Runs once the condition becomes false.

Common Python Loops Mistakes

Forgetting to update a while loop

Don't
count = 1
while count <= 3:
    print(count)
Do
count = 1
while count <= 3:
    print(count)
    count += 1

count never changes in the first version, so it prints 1 forever.

Expecting range() to include the end

Don't
for i in range(1, 10):
    print(i)   # stops at 9
Do
for i in range(1, 11):
    print(i)   # 1 to 10

Resetting the total inside the loop

Don't
for n in [4, 5, 6]:
    total = 0
    total += n
print(total)   # 6
Do
total = 0
for n in [4, 5, 6]:
    total += n
print(total)   # 15

Python Loops in Real Projects

Loops in real programs

A music app loops through a playlist to show each song, a school system loops through every student to print report cards, and a game runs a while loop that keeps drawing frames until the player quits. Whenever you hear "for each" or "until", think of a loop.

Python Loops FAQ

Is there a do-while loop in Python?

No. The usual pattern is while True: with a break once the exit condition is met. The body always runs at least once, which is exactly what a do-while loop guarantees in other languages.

How do I loop backwards in Python?

Use a negative step in range(), such as range(10, 0, -1) for 10 down to 1, or wrap a sequence in reversed(): for item in reversed(items):. reversed() doesn't copy or change the original list.

Can I change a list while looping over it?

Changing a list's length while a for loop runs over it causes skipped or repeated items. Loop over a copy, for item in items[:]:, or build a new list of the items you want to keep, often with a list comprehension.

Why doesn't range() accept decimal steps like 0.5?

range() works only with integers. For decimal steps, loop over whole numbers and divide, for example for i in range(0, 11): value = i / 2, which gives 0.0 to 5.0 in steps of 0.5. This avoids the rounding drift you get from adding 0.5 repeatedly.

What is the difference between break, continue and pass?

break leaves the loop completely. continue skips the rest of the current pass and moves to the next item. pass does nothing at all; it is a placeholder for a block you haven't written yet.

Python Loops Exercises

Answer each one and check it instantly. If you get stuck, open the hint before the answer.

Fill in the blankseasy

Complete the loop so it prints the numbers 0 to 4.

 i  range(5):
    print(i)
Predict the outputeasy

What numbers does this print?

for i in range(2, 9, 3):
    print(i)
Predict the outputmedium

What does this print?

n = 1
while n < 20:
    n = n * 3
print(n)
Multiple choicemedium

Which keyword skips the rest of the current pass and moves to the next one?

Predict the outputmedium

What does this print?

total = 0
for n in range(1, 5):
    total += n
print(total)

Python Loops Quiz

5 questions to check what you learned.

  1. Which numbers does range(4) produce?

    • 1, 2, 3, 4
    • 0, 1, 2, 3, 4
    • 0, 1, 2, 3
    • 4
  2. Which loop is best when you don't know how many repeats you need?

    • for
    • range
    • if
    • while
  3. What does break do inside a loop?

    • Exits the loop immediately
    • Pauses the loop for a moment
    • Skips one pass
    • Restarts the loop
  4. How many times does print run here: for i in range(10, 0, -2): print(i)?

    • 4
    • 5
    • 6
    • 10
  5. What does continue do inside a loop?

    • Ends the loop completely
    • Restarts the loop from the beginning
    • Skips the rest of this pass and moves on to the next one
    • Pauses the program