Skip to content
Educora
Beginner16 min5 / 42

Loops: for and while

Learn to repeat work: for with range(), while, and the loop controls break and continue.

Check yourself
In this lesson you will learn
  • Go through the characters of a string and a range of numbers with for
  • Use the start, stop and step of range()
  • Write a while loop that repeats as long as a condition is true
  • Control a loop with break and continue

Imagine you need to print the numbers from 1 to 100. Write print 100 times? Certainly not! The greatest strength of computers is repeating the same job without getting tired. That is what loops are for: a few lines of code can run thousands of times.

The for loop

A for loop takes the items of a sequence one by one and runs the same block for each of them. In the code below, the variable letter takes the values 'B', 'a', 'k' and 'u' in turn. Each repetition of a loop is called an iteration.

Python
for letter in 'Baku':
    print(letter)
▸ Expected output
B
a
k
u

To loop over numbers, use the range() function. It creates a sequence of numbers: range(1, 11) gives the numbers from 1 to 10 — just like with slices, the stop value is not included. Let's print the times table for 7:

Python
for i in range(1, 11):
    print(f'7 x {i} = {7 * i}')
▸ Expected output
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70
CallNumbers it givesExplanation
range(5)0, 1, 2, 3, 4starts at 0, 5 is not included
range(2, 6)2, 3, 4, 5start and stop
range(0, 10, 3)0, 3, 6, 9the third number is the step
range(5, 0, -1)5, 4, 3, 2, 1a negative step counts down

Building up a result

A very common loop pattern: create an “accumulator” variable before the loop, then add something to it on every iteration. For example, let's add up all the numbers from 1 to 100:

Python
total = 0
for n in range(1, 101):
    total += n
print('Sum:', total)
▸ Expected output
Sum: 5050
Python
for i in range(1, 5):
    print('*' * i)
▸ Expected output
*
**
***
****
Multiplying a string by a number inside a loop draws a simple pattern. Replace range(1, 5) with range(1, 8).

The while loop

for is handy when you know in advance how many times to repeat. But what if you don't? Then the while loop helps: it repeats its block as long as a condition is true. Murad saves 15 manat a week to buy headphones that cost 100 manat. How many weeks will he need?

Python
price = 100
saved = 0
weeks = 0
while saved < price:
    saved += 15
    weeks += 1
print(f'After {weeks} weeks Murad has {saved} AZN.')
▸ Expected output
After 7 weeks Murad has 105 AZN.

break and continue

break stops the loop completely right away — handy when you have found what you were looking for. For example, let's search for the first number that divides by both 5 and 7:

Python
for n in range(1, 100):
    if n % 5 == 0 and n % 7 == 0:
        print('Found:', n)
        break
▸ Expected output
Found: 35

continue does not stop the loop; it only skips the rest of the current iteration and moves on to the next one. The code below counts the characters in a text, ignoring spaces:

Python
text = 'Python is fun'
count = 0
for ch in text:
    if ch == ' ':
        continue
    count += 1
print('Letters:', count)
▸ Expected output
Letters: 11
Exercise

Using a for loop and range(), print the squares of the numbers from 1 to 5 — each on its own line, in the form 3 x 3 = 9.

Exercise · Python
# print the squares of 1..5 like: 3 x 3 = 9
▸ Expected output
1 x 1 = 1
2 x 2 = 4
3 x 3 = 9
4 x 4 = 16
5 x 5 = 25
Exercise

Use a while loop to find the sum of the digits of n = 4096 and print it after the words Digit sum:. The loop should run until n becomes zero.

Exercise · Python
n = 4096
total = 0
# while n is greater than 0:
#     add the last digit of n to total
#     remove the last digit from n
# print Digit sum: and total
▸ Expected output
Digit sum: 19

Key points

  • for runs its block once for every item of a sequence.
  • range(start, stop, step) produces numbers; stop is not included.
  • while repeats as long as its condition is true — make sure the condition eventually becomes false.
  • break ends the loop completely; continue jumps to the next iteration.
  • An accumulator variable is created before the loop and updated on each iteration.

Check yourself

10 questions. Every correct answer earns XP.

1 / 10
Which numbers does range(1, 5) give?