Loops
for letter in "Sun":
print(letter)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:
| Code | Numbers |
|---|---|
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
breakleaves the loop immediately.continueskips 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:forgoes through items;range(a, b)stops before b;whilerepeats while a condition holds;breakexits,continueskips.
See it in actionA loop repeats its body
The arrow goes round and round. Watch i and total change on every pass.
Try it yourselfExample 1: for with range
Prints each number and its square. Try range(1, 11).
Output appears hereCount to five
Fill the blanks so the loop prints the numbers 1 to 5, one per line.
for i in (1, ): print(i)
Example 2: Adding things up
The accumulator pattern sums the numbers and counts the even ones.
Output appears hereA total that resets
This should add 1 + 2 + … + 10 and print 55, but it prints the wrong answer. Fix it.
Example 3: while loop with break
The loop has no natural end, so break stops it once the condition is met.
Output appears hereStop at the password
Fill the blanks so the loop keeps asking until the input is open, then prints Welcome.
while : word = input() if word == "open": print("Welcome")
Example 4: Countdown and continue
continue skips the printing step for the number 3.
Output appears hereMultiplication 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
Example 5: Nested loops make patterns
The inner loop runs fully for each row of the outer loop.
Output appears hereStar 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*
**
***
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.
Example 6: enumerate, zip and reversed
Three ways to walk through a sequence more clearly than with indexes.
Output appears hereExample 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.
Output appears here3Level 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".
Example 8: Double loop vs one pass
Both count the steps they take. Increase n to 2000 and compare.
Output appears hereExample 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.
Output appears hererange(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).What does this print?
total = 0
for i in range(2, 11, 3):
total += i
print(total)50 graded problems are waiting in Topic Practice.