Loops: Repeating Actions

Learn how to use for loops and while loops to repeat code automatically instead of writing it out over and over.

~26 min Beginner

Why loops, and the for loop

Imagine you want to print the numbers 1 to 10. You could write 10 print statements. But what if you need 1 to 1000? That is not practical. Loops solve this. A loop lets you run the same block of code many times without writing it out again and again.

A for loop runs a block of code once for each item in a sequence. The most common use is with the range() function, which generates a sequence of numbers:

for i in range(5):
    print(i)
0
1
2
3
4

Here i is the loop variable. Each time around, Python puts the next number into i and runs the indented block. One trip through the block is called an iteration. range(5) gives you 0, 1, 2, 3, 4. It starts at 0 and stops before 5, so there are exactly 5 numbers.

You can use any name for the loop variable, but short names like i, or a meaningful one like number, are common.

range with a start and a step

To start at a different number, give range() two values. The first is where to start (included), the second is where to stop (not included). To go from 1 to 10:

for i in range(1, 11):
    print(i)   # prints 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

You can also add a step, meaning how much to increase by each time:

for i in range(0, 20, 5):
    print(i)   # prints 0, 5, 10, 15

A negative step counts down:

for i in range(5, 0, -1):
    print(i)   # prints 5, 4, 3, 2, 1
  • range(5) gives 0 to 4
  • range(1, 6) gives 1 to 5
  • range(0, 20, 5) gives 0, 5, 10, 15
  • range(5, 0, -1) gives 5, 4, 3, 2, 1

The most common slip is expecting range(5) to include 5. It does not. Remember that the stop number is never part of the result.

Looping over a string

A for loop can go through each character in a string, because a string is a sequence of characters:

for letter in "Python":
    print(letter)
P
y
t
h
o
n

You are not limited to numbers. Whatever the sequence holds, the loop variable takes each value in turn. This is useful, for example, to count something in a word:

word = "banana"
count = 0
for letter in word:
    if letter == "a":
        count += 1
print(count)   # 3

Later you will loop over lists and dictionaries in exactly the same way.

The while loop

A while loop keeps repeating as long as a condition is true. When the condition becomes false, the loop stops:

count = 1
while count <= 5:
    print(count)
    count += 1
1
2
3
4
5

Python checks the condition before every round. A normal while loop has three parts: something to start with (count = 1), a condition (count <= 5), and a change that moves it closer to stopping (count += 1).

Be careful with while loops. If the condition never becomes false, the loop runs forever. This is called an infinite loop, and it will freeze your program. Always make sure something inside the loop moves it closer to stopping.

count = 1
while count <= 5:
    print(count)
    # forgot count += 1, so this never ends!
Stuck in a loop? press Ctrl + C in the terminal to stop a running program.

When should you pick which? Use for when you know how many times to repeat, or you have a collection to go through. Use while when you repeat until something happens.

break and continue

Two special keywords let you control a loop from the inside. break immediately stops the loop and exits it:

for i in range(10):
    if i == 5:
        break   # stop the loop when i reaches 5
    print(i)
# prints 0, 1, 2, 3, 4

continue skips the rest of the current round and jumps to the next one:

for i in range(10):
    if i % 2 == 0:
        continue   # skip even numbers
    print(i)
# prints 1, 3, 5, 7, 9

An easy way to remember them: break means "I am done with the whole loop", continue means "skip this one and keep going". A good use of break is to stop searching once you found what you were looking for:

names = ["Ann", "Bob", "Cara", "Dev"]
for name in names:
    if name == "Cara":
        print("Found Cara!")
        break

while for input, and adding things up

A very common and practical use of while loops is to keep asking the user for input until they give a valid answer:

while True:
    answer = input("Type yes or no: ")
    if answer == "yes" or answer == "no":
        break
    print("Please type exactly yes or no.")

print(f"You chose: {answer}")

while True runs forever on its own, but it exits as soon as the user gives a valid answer. This pattern is used very often in real programs. The second very common pattern is accumulating: start a total at zero and add to it each round:

# Add up all numbers from 1 to 100
total = 0
for i in range(1, 101):
    total += i

print(f"The sum of 1 to 100 is {total}.")
The sum of 1 to 100 is 5050.

Start with a variable that holds the "nothing yet" value, 0 for a total, then update it inside the loop. The same idea builds up a count, a product, or a string.

Nested loops

You can put a loop inside another loop. The inner loop completes all its rounds for each single round of the outer loop:

for row in range(1, 4):
    for col in range(1, 4):
        print(f"Row {row}, Col {col}")
Row 1, Col 1
Row 1, Col 2
Row 1, Col 3
Row 2, Col 1
...and so on

The outer loop runs 3 times and the inner loop runs 3 times each, so the print line runs 3 x 3 = 9 times. Think of a clock: the minutes hand goes around fully for each step of the hours hand.

Nested loops are perfect for tables and grids. For example, a multiplication table:

for a in range(1, 4):
    for b in range(1, 4):
        print(a * b, end=" ")
    print()
1 2 3 
2 4 6 
3 6 9 

The end=" " keeps the numbers on one line, and the plain print() at the end of each outer round moves to the next line.

Loop patterns and else

A few patterns appear again and again. Here are the ones worth knowing:

# 1. Counting how many items match
count = 0
for n in range(1, 21):
    if n % 3 == 0:
        count += 1
print(count)     # 6

# 2. Finding the largest value
biggest = 0
for n in [4, 17, 9, 12]:
    if n > biggest:
        biggest = n
print(biggest)   # 17

# 3. Building a string
result = ""
for letter in "abc":
    result += letter.upper()
print(result)    # ABC

Python loops also have an else part that runs only if the loop finished without hitting break. It is great for "search and report" jobs:

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

Do not worry if for ... else feels odd at first. You can write plenty of good programs without it.

Common mistakes

  • Off by one. range(10) stops at 9. If you need 1 to 10, write range(1, 11).
  • Infinite while loops. Check that the loop variable changes, and that the condition can become false.
  • Changing the wrong variable. In for i in range(5), assigning to i inside the loop does not change the next round.
  • Missing indentation. Only the indented lines repeat. A line outside the block runs just once.
  • Forgetting to reset a total. Set total = 0 before the loop, not inside it.
for i in range(3):
    print("Hi")
print("Done")
Hi
Hi
Hi
Done

The last print is outside the loop, so it runs one time only. Looking carefully at indentation tells you exactly what repeats.

Key takeaways

  • A loop repeats a block of code. One trip through is an iteration
  • for goes through a sequence, and range(start, stop, step) makes number sequences that stop before the end number
  • while repeats as long as its condition is true, so something inside must move it toward stopping
  • break leaves the loop and continue skips to the next round
  • while True with break is the standard way to keep asking until the input is valid
  • Start totals at 0 and add to them inside the loop
  • Nested loops run the inner loop fully for every round of the outer loop
Sign up to track your progress Mark lessons as read and pick up where you left off Sign up free to unlock this practice Your first practice lesson is free to try. Create an account to unlock the rest and save your progress