Designing with functions
Break a task into small functions that each do one thing, write them top-down from a main function, and test each one on its own with chosen inputs.
It opens on
Our prime counter has a function is_prime that we can call on its own. Is 91 prime?
Why it matters
Programs beyond a screenful are only manageable as small functions with clear jobs; it is how every project, lab and exam question with "write a program that" is best approached, and testing pieces separately finds bugs where they are, not three calls away.
Good to know first
- Default and keyword arguments and docstrings: a docstring states what a function takes and returns
- Loop patterns: counting with an accumulator
- While loops: a loop that stops on a condition
Step by step
Splitting a task
Break "count the primes up to a limit" into functions with one job each, drawn as a call tree, and call one piece on its own.
smallest_divisor tries d = 2, 3, 4 and so on, returning the first that divides n, and stops once d × d passes n, because a larger divisor would pair with a smaller one already tried. If none divides, n itself is returned.
the two lowest functions
A common mix-up
Splitting into functions makes a program longer and so worse.
In fact: The parts are each short and testable, and the whole is easier to read and fix.
Testing each piece
Choose test inputs for a function, including edge cases, compare with expected results, and find a bug in one piece.
smallest_divisor passed all three, 3, 7 and 97.
A common mix-up
If the whole program prints a believable answer, its pieces are right.
In fact: count_primes starts at 2, so the is_prime(1) bug never showed in the count, yet is_prime was wrong.
One job each, and reuse
Write count_primes and main from the tested pieces, keep input and printing out of the computing functions, and reuse is_prime for a new task.
Typing 30 at Up to? made main print 10 primes up to 30.
A common mix-up
A function should print its result so we can see it.
In fact: Printing makes it hard to reuse or test; return the value and let main print.
Try it
What does smallest_divisor(15) return, and after how many values of d?Answer
3, after trying d = 2 and then 3
Hint: 15 % 2 is 1
Choose three test inputs for is_prime and their expected results, one of them an edge case.Answer
For example is_prime(97) True, is_prime(9) False and is_prime(2) True
Hint: Include a square and the smallest prime
Using is_prime, write count_primes_between(a, b) for the primes from a to b, and give its result for 10 and 20.Answer
count_primes with range(a, b + 1) in place of range(2, limit + 1), and parameters a and b; it gives 4, for 11, 13, 17 and 19
Hint: Change only the range
Without running the whole program, what do smallest_divisor(91) and is_prime(91) return?Answer
7, since 91 = 7 × 13, and so False.
What did that first version return for is_prime(1), and why?Answer
True, since smallest_divisor(1) skips the loop, 2 × 2 > 1, and returns 1, which equals n.
