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

Ask one small question

How would you count the prime numbers up to 20? You'd go through the numbers one at a time, and for each one ask: is this a prime? If yes, count it.

That's two jobs: walking through the numbers, and answering the question about one number. Keep them apart. Write the question as its own function, which returns true or false. A function that answers a yes-or-no question gets a name that sounds like a question, such as is_prime.

One job per function, with a name that says what it answers.

The helper, and the loop that uses it

A prime is a number bigger than 1 with no divisors except 1 and itself. To check, try every number from 2 up to just below it. If any of them divides it evenly, it is not a prime, so return false at once. If none do, return true.

Now the counting loop becomes easy to read: for each number, if it is prime, add one. You can test the helper alone, and then trust it inside the loop.

Test the small helper first, then use it in the bigger one.
In code
def is_prime(k):
    if k < 2:
        return False
    for d in range(2, k):
        if k % d == 0:
            return False
    return True
Counting primes up to 10
2
0
3
1
4
2
5
3
6
4
7
5
8
6
9
7
10
8
k
k
2
count
1

Ask the helper about 2. Nothing between 2 and 2 can divide it, so it is a prime. The count is 1.

Move 1 of 6