LearnPy Hub
Control FlowBeginnerLesson 8 of 32

Loops

Watch the ideaA loop repeats for each item
for letter in "Sun":
    print(letter)
string
S0
u1
n2

A for loop visits the characters of the string one at a time.

1Level 1 · BasicsBasics

Computers are brilliant at doing the same thing again and again without getting bored. A loop repeats a block of code. Python has two kinds: for and while.

for loops: repeat for each item

A for loop goes through a sequence one item at a time. A string is a sequence of characters:

for letter in "Dhaka":
    print("Letter:", letter)

Each time round the loop, the variable letter holds the next character. The indented block is the loop's body, just like with if.

range(): counting

range() produces numbers for a for loop:

CodeNumbers
range(5)0, 1, 2, 3, 4
range(1, 6)1, 2, 3, 4, 5
range(0, 10, 2)0, 2, 4, 6, 8
range(5, 0, -1)5, 4, 3, 2, 1

The stop number is never included. To count from 1 to n, write range(1, n + 1).

The accumulator pattern

A very common job: start with an empty total and add to it each time round.

total = 0
for n in range(1, 6):
    total += n
print(total)   # 15

while loops: repeat while a condition is true

Use while when you don't know in advance how many times to repeat:

n = 1
while n < 100:
    n = n * 2
print(n)   # 128

Make sure something inside the loop eventually makes the condition False. Otherwise you get an infinite loop. (The editor stops programs that run too long, so it's safe to experiment.)

break and continue

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

Nested loops

A loop inside a loop runs the inner loop completely for every round of the outer loop. That's how you print grids, tables and star patterns.

Key points: for goes through items; range(a, b) stops before b; while repeats while a condition holds; break exits, continue skips.

See it in actionA loop repeats its body

The arrow goes round and round. Watch i and total change on every pass.

Step-by-step

Try it yourselfExample 1: for with range

Prints each number and its square. Try range(1, 11).

example_1.py
Output appears here
Fill in the blanks

Count to five

Fill the blanks so the loop prints the numbers 1 to 5, one per line.

blanks.py
for i in (1, ):
    print(i)

Example 2: Adding things up

The accumulator pattern sums the numbers and counts the even ones.

example_2.py
Output appears here
Fix the bug

A total that resets

This should add 1 + 2 + … + 10 and print 55, but it prints the wrong answer. Fix it.

buggy.py

Example 3: while loop with break

The loop has no natural end, so break stops it once the condition is met.

example_3.py
Output appears here
Fill in the blanks

Stop at the password

Fill the blanks so the loop keeps asking until the input is open, then prints Welcome.

blanks.py
while :
    word = input()
    if word == "open":
        
print("Welcome")

Example 4: Countdown and continue

continue skips the printing step for the number 3.

example_4.py
Output appears here
Your turn

Multiplication table

Read a number and print its table from 1 to 5 in the form 7 x 1 = 7.

Example input7Expected output7 x 1 = 7 7 x 2 = 14 7 x 3 = 21 7 x 4 = 28 7 x 5 = 35

my_code.py

Example 5: Nested loops make patterns

The inner loop runs fully for each row of the outer loop.

example_5.py
Output appears here
Your turn

Star triangle

Read a number n and print a triangle of stars with n rows: 1 star, then 2, and so on. For 3 the output is *, **, ***.

Example input3Expected output* ** ***

my_code.py

2Level 2 · IntermediateLooping patterns you'll use every day

enumerate() and zip()

for i, letter in enumerate(word, start=1): gives a counter with each item. for a, b in zip(word1, word2): walks two sequences side by side. Both work on lists too, which come next.

Looping backwards and in steps

range(10, 0, -1) counts down; reversed(word) walks a sequence from the end without changing it.

for ... else

A loop's else block runs only if the loop finished without break. Perfect for searches: "if we never found it, say so".

Common patterns

Counting, summing, finding the maximum, and building up a result (such as a new string) are the four patterns behind most loop problems.

See it in actionfor-else finds a prime

Watch the loop break when a divisor is found, and the else run when none is.

Step-by-step

Example 6: enumerate, zip and reversed

Three ways to walk through a sequence more clearly than with indexes.

example_6.py
Output appears here

Example 7: The four patterns in one program

Count, sum, max and build (a string), all in a single pass over a week of temperatures. Change them in the Input box.

example_7.py
Output appears here

3Level 3 · AdvancedThinking about loop speed and clever loops

How many steps?

One loop over n items takes about n steps; a loop inside a loop takes about n × n. With n = 100,000 that's 10 billion steps, far too slow. Spotting this is the first skill of fast programs.

Two pointers

One index starts at the left and one at the right, and they walk towards each other. On a string this checks a palindrome without building a reversed copy; on numbers in order it finds a pair with a given sum in a single pass instead of a double loop.

A formula beats a loop

Sometimes maths removes the loop entirely: the sum 1 + 2 + ... + n is n * (n + 1) // 2. One step instead of n.

while True with break

For "repeat until something happens" loops (menus, games, simulations), while True: with a clear break is often the cleanest shape.

See it in actionTwo pointers meet in the middle

Watch left and right move toward each other, comparing one pair of letters at a time. Try "rocket".

Step-by-step

Example 8: Double loop vs one pass

Both count the steps they take. Increase n to 2000 and compare.

example_8.py
Output appears here

Example 9: A formula beats a loop

The loop takes a million steps; the formula takes one. Try n = 10_000_000 and feel the difference.

example_9.py
Output appears here
Rememberrange(5) is 0, 1, 2, 3, 4. It never includes the stop value. If your loop runs one time too few, you probably need range(1, n + 1).
Exercise · predict the output

What does this print?

total = 0
for i in range(2, 11, 3):
    total += i
print(total)
Quick quiz · 5 questions
1. Which statement skips to the next round of a loop?
2. Which numbers does range(3) produce?
3. Which loop is best when you don't know how many repetitions you need?
4. How many times does print run? for i in range(3), and inside it for j in range(4), print(i, j).
5. What causes an infinite while loop?
Ready to practice loops?

50 graded problems are waiting in Topic Practice.

Practice this topic →
Python Loops · LearnPy Hub