Exit
  1. Learn
  2. Check
  3. Solve
  4. Reflect

A loop with a question inside

A teacher looks at every child in the class and counts only those wearing a red shirt. She doesn't count everyone, only the ones who pass the test.

In code, that's a loop with an if inside it. Make a counter box that starts at zero. On each pass, ask the question about the current number. If the answer is true, add one to the counter. If not, do nothing and move on to the next number.

Count only when the test is true: put the adding inside the if.
In code
count = 0
for i in range(1, n + 1):
    if i % 3 == 0:
        count = count + 1

Is it a multiple?

How do you ask whether a number is a multiple of 3? Think of the remainder. If you divide by 3 and nothing is left over, then the number fits into whole groups of 3. A remainder of zero means it is a multiple.

You can ask for two things at once with or. Is the number a multiple of 3, or a multiple of 5? Counting from 1 to 10, the answers are 3, 5, 6, 9 and 10.

A remainder of zero: means it divides evenly.
In code
if i % 3 == 0 or i % 5 == 0:
    count = count + 1
Multiples of 3 or 5, from 1 to 10
1
0
2
1
3
2
4
3
5
4
6
5
7
6
8
7
9
8
10
9
i
i
2
count
0

1 and 2 are not multiples of 3 or 5, so the count stays at 0.

Move 1 of 8