A loop can repeat more than printing; it can repeat a calculation on the same variable. To work out 3×3×3×3, start with num = 1 and multiply by 3 four times:
num = 1
for i in range(4):
num = num * 3
print(num)81
Where you put print matters: indented, it prints on every turn; not indented, it prints once at the end:
num = 1
for i in range(4):
num = num * 3
print(num)3 9 27 81
Using i in the calculation
The loop variable changes on each turn, so you can use it in the calculation. range(2, 7) gives 2, 3, 4, 5, 6, so this works out 2×3×4×5×6:
num = 1
for i in range(2, 7):
num = num * i
print(num)720
Running totals and +=
Same idea with adding: a variable starts at 0 and grows on each turn. total += i is short for total = total + i:
total = 0
for i in range(1, 11):
total += i
print("1 + 2 + ... + 10 = " + str(total))1 + 2 + ... + 10 = 55
if inside the loop
Put an if inside the loop to count or add only the numbers that pass a test. Here we count the multiples of 3 from 1 to 20:
count = 0
for i in range(1, 21):
if i % 3 == 0:
count += 1
print(count)6
total = 0 or count = 0 before the loop. Inside the loop it would reset to 0 on every turn.Practice
Work out 5×5×5: set num to 1, repeat num = num * 5 three times with a for loop, then print num once.
Press Run to see the result. Multiply the numbers from 2 to 9 in order using the loop variable i, then print the result.
Press Run to see the result. Start with num = 5040, divide it by i for i from 1 to 5 (range(1, 6)), then print num.
Press Run to see the result. Add 5 to num using += so it prints 5.
num = 0 ___ print(num)
Press Run to see the result. Print the 7 times table from 7 x 1 = 7 to 7 x 5 = 35, one line each, letting the computer calculate the result with the loop variable i.
Hint
Userange(1, 6) and str().Press Run to see the result. You save 15 pounds every day for 7 days. Use a loop and +=, and print the total each day as Day 1: 15, Day 2: 30 ... up to Day 7: 105.
Press Run to see the result. Add up only the even numbers from 1 to 20 using an if inside the loop, then print Sum of evens: 110.
Hint
A number is even wheni % 2 == 0.Press Run to see the result. Key points
- For repeated multiplying start with
num = 1; for adding start withtotal = 0, before the loop. - You can use
iin the calculation:num = num * i. x += 3meansx = x + 3; an if inside the loop picks which values to add or count.