Python Programming · High School (11–12) · 1 course, 10 worked problems, 20 practice questions
Programs rarely work the first time, so programmers test and debug them. Testing means running code with chosen inputs and checking the output against what you expect. A simple test uses assert, which stops the program if a condition is false. Good tests include normal values, edge cases and wrong input. Debugging means finding the cause of a fault. You read the traceback, print values at key points, or step through the code line by line. Logic errors are the hardest to find, because the program runs but gives the wrong answer.
assertChoose an answer, then check it. Each one shows a full explanation.
add(a, b) has a bug: it returns a - b. Which test would let the bug slip through?
Why does assertEqual(0.1 + 0.2, 0.3) fail, while assertAlmostEqual(0.1 + 0.2, 0.3) passes?
A bug hides somewhere in 64 lines. About how many checks does bisection need to find its line?
Each one has a hint, the key idea and a full worked solution.
What does len("".split(" ")) give?
assert 2 + 2 == 4, "maths" is run. What is shown?
assert len([]) > 0, "empty" is run. What happens?
A function double(n) returns n * 3. The test self.assertEqual(double(2), 4) is run. What does the report say about the values?
In a test run, the line of letters is .F.. What does it mean?
Which assert method compares 0.1 + 0.2 with 0.3 correctly?
def last(items): return items[-1]. What does last([]) do?