Fixing Functions
Every program in this unit so far has done what it was written to do. Real code often does not, and reading broken code is a separate skill from writing…
Reading code that does not work
Every program in this unit so far has done what it was written to do. Real code often does not, and reading broken code is a separate skill from writing working code. It is worth practising on purpose.The method never changes. First say the intent in one sentence: what is this program supposed to produce? Then run it in your head, one line at a time, and stop at the first place where what happens and what was intended come apart. Do not begin by hunting for the fault. Begin by knowing what the program was for, because a line can only be wrong compared to something.
Three questions that catch most broken functions
Does the function hand its answer back? A function that only prints its answer hands the caller None.Does the caller keep what comes back? A returned value that is not stored, printed or used in a calculation is gone the moment the call ends.
Does the name exist yet? Python reads a file from the top down, so a call written above the def it needs has nothing to call.
Counting how many times a body runs
A call runs the body once. Every time. Two calls run it twice, even when they are written on the same line, and even when they are handed the same argument and work out the same answer.Doing the same work twice
Two programs can be equally correct and still not be equally good. Correct is not the end of the question; how much work the program does to get there is the other half of it.