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.
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.
def is_prime(k):
if k < 2:
return False
for d in range(2, k):
if k % d == 0:
return False
return True- 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.