- Go through the characters of a string and a range of numbers with
for - Use the start, stop and step of
range() - Write a
whileloop that repeats as long as a condition is true - Control a loop with
breakandcontinue
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.
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:
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
| Call | Numbers it gives | Explanation |
|---|---|---|
range(5) | 0, 1, 2, 3, 4 | starts at 0, 5 is not included |
range(2, 6) | 2, 3, 4, 5 | start and stop |
range(0, 10, 3) | 0, 3, 6, 9 | the third number is the step |
range(5, 0, -1) | 5, 4, 3, 2, 1 | a 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:
total = 0
for n in range(1, 101):
total += n
print('Sum:', total)▸ Expected output
Sum: 5050
for i in range(1, 5):
print('*' * i)▸ Expected output
* ** *** ****
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?
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:
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:
text = 'Python is fun'
count = 0
for ch in text:
if ch == ' ':
continue
count += 1
print('Letters:', count)▸ Expected output
Letters: 11
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.
# 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
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.
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
forruns its block once for every item of a sequence.range(start, stop, step)produces numbers;stopis not included.whilerepeats as long as its condition is true — make sure the condition eventually becomes false.breakends the loop completely;continuejumps 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.
range(1, 5) give?