Skip to content
Qyubie Learn

Python tutorial · Beginner

Loops in Python: for, while, and When to Use Each

Learn how Python's for and while loops work, how range() counts, and how to avoid endless loops — with exercises you can run in your browser.

  • Qyubie Learn Editorial Team
  • Published
  • 11 min read

Includes 3 exercises and 2 quick checks you can do right here.

A loop lets a program repeat work without you writing the same line again and again. Printing a times table, adding up a list of scores, or asking for a password until it's right — all of these are loops.

By the end of this guide you will be able to:

  • write a for loop over a list and over a range of numbers,
  • write a while loop that stops at the right time,
  • choose between the two, and
  • use break and continue without getting lost.

What you need: you should know what a variable is and how print() works. Everything else is explained here, and every example runs right on this page — press Run Python under any code. (The first run loads Python into your browser, which takes a few seconds.)

Why loops exist

Imagine printing the numbers 1 to 5:

print(1)
print(2)
print(3)
print(4)
print(5)

That works, but what about 1 to 500? Or a list of names you don't know in advance? A loop says "do this for each item" or "keep doing this while something is true" — once.

The for loop: one turn per item

A for loop walks through a sequence — a list, a string, a range of numbers — and runs its body once for each item. The variable after for holds the current item on each turn.

Try it · Python

Three things to notice:

  1. The line ends with a colon :.
  2. The body is indented (four spaces is the convention). Indentation is how Python knows which lines belong to the loop.
  3. print("Done!") is not indented, so it runs once, after the loop finishes.

A string is a sequence of characters, so you can loop over it too:

Try it · Python

Counting with range()

When you need numbers rather than items, use range(). It produces numbers on demand, and it has three forms:

CallNumbers it givesRemember
range(5)0, 1, 2, 3, 4starts at 0, stops before 5
range(1, 6)1, 2, 3, 4, 5start is included, stop is not
range(0, 10, 2)0, 2, 4, 6, 8the third number is the step

The rule that trips most beginners: the stop number is never included. range(1, 6) stops at 5.

Try it · Python

You can also count backwards with a negative step:

Try it · Python

Quick check

What does this program print?
for i in range(2, 8, 2):
    print(i)

Adding things up: the accumulator pattern

A very common job is to combine many values into one result — a total, a count, a longest word. The pattern is always the same:

  1. Create a variable before the loop with a starting value.
  2. Update it inside the loop.
  3. Use it after the loop.

Try it · Python

A frequent mistake is putting total = 0 inside the loop. Then it resets on every turn and you only ever get the last score.

Exercise · Python

Sum of 1 to 100

Use a for loop with range() to add up every whole number from 1 to 100, then print the total. Your program should print just the number.

Expected output
5050
Hint

range(1, 101) gives 1 up to 100 — remember the stop number isn't included. Inside the loop, add the current number to total.

Show a solution

Try it yourself first — you learn more from a wrong attempt than from reading an answer.

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

The while loop: repeat until a condition changes

A while loop doesn't walk through items. It keeps going as long as a condition is true, checking the condition before every turn.

Try it · Python

Read it as: while count is more than 0, print it and make it smaller. When count becomes 0, the condition is false and the loop ends.

Watch out for endless loops

If nothing inside the loop ever makes the condition false, the loop never stops. Here count never changes, so count > 0 stays true forever:

count = 3
while count > 0:
    print("This never ends")   # count is never made smaller!

When you write a while loop, ask yourself: which line moves us closer to stopping? If you can't point to one, the loop is endless. (On this site a program that runs longer than 10 seconds is stopped for you.)

for or while? How to choose

Use for when…Use while when…
you have a list, string, or range to go throughyou don't know how many turns you need
you know how many times to repeatyou repeat until something happens (correct input, a target reached)
e.g. "print every student's name"e.g. "keep doubling until the value passes 1000"

Most loops you write will be for loops. Reach for while when the number of turns depends on what happens during the loop.

Try it · Python

You couldn't easily write that with for, because you don't know the number of turns in advance.

break and continue

Two keywords change the flow inside any loop:

  • break leaves the loop immediately.
  • continue skips the rest of this turn and goes to the next one.

Try it · Python

Use them sparingly. A loop with several breaks is hard to follow; often a clearer condition does the same job.

Quick check

In a loop, what does continue do?

Loops inside loops

A loop body can contain another loop. The inner loop runs completely for each turn of the outer loop — useful for tables and grids.

Try it · Python

Exercise · Python

Multiplication table row

Print the 7 times table from 7 × 1 to 7 × 5, one line each, in exactly this form: 7 x 1 = 7.

Expected output
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
Hint

Loop with range(1, 6). Inside, print(number, "x", i, "=", number * i) — print puts a space between each value for you.

Show a solution

Try it yourself first — you learn more from a wrong attempt than from reading an answer.

number = 7
for i in range(1, 6):
    print(number, "x", i, "=", number * i)

Exercise · Python

Count the passing scores

A score of 75 or higher passes. Count how many scores in the list pass, and print only that count.

Expected output
4
Hint

Loop over scores. Inside, use if score >= 75: and add 1 to passed.

Show a solution

Try it yourself first — you learn more from a wrong attempt than from reading an answer.

scores = [80, 62, 75, 91, 70, 88, 74]
passed = 0
for score in scores:
    if score >= 75:
        passed = passed + 1
print(passed)

Common mistakes

  • Forgetting the colon after for ... or while ... — Python reports a SyntaxError.
  • Wrong indentation — a line that should be in the loop isn't indented, so it runs only once (or vice versa).
  • Off-by-one with range() — range(1, 10) stops at 9. If you need 10, write range(1, 11).
  • Resetting an accumulator inside the loop — create total = 0 before the loop, not inside it.
  • A while loop that never ends — make sure something inside changes the condition.

Summary

  • for repeats once per item in a sequence; range(start, stop, step) gives numbers, and stop is never included.
  • while repeats as long as a condition is true — always make sure something changes it.
  • The accumulator pattern: start a variable before the loop, update it inside, use it after.
  • break leaves a loop; continue skips to the next turn.

Next steps: try changing the examples above — different ranges, different lists — and predict the output before you press Run. Predicting first is one of the fastest ways to really understand loops.

References and further reading