When the Operator Is Wrong
The errors section ended with a distinction worth carrying forward. A syntax error stops the program before it starts. A run-time error stops it partway…
The bug that does not crash
The errors section ended with a distinction worth carrying forward. A syntax error stops the program before it starts. A run-time error stops it partway. A logic error lets it run all the way to the end and hands back a wrong answer.Picking the wrong arithmetic operator is the easiest logic error there is to write. Every operator in this unit takes the same two numbers and returns a value, so swapping one for another changes the answer and nothing else. Nothing is underlined, nothing is raised, and the program prints something that looks exactly like a result.
Reading an expression against its intent
Debugging arithmetic is not a matter of staring harder at the numbers. It means naming what a line is supposed to hand back, then asking whether the operator on that line is capable of handing that back.• A count of whole things cannot come from a single slash. True division always returns a float.
• A leftover cannot come from two slashes. Floor division throws the leftover away.
• A count of whole things cannot come from a percent sign either. Modulus returns only the part that did not fit.
Carrying a leftover forward
A leftover is the input to the next step, not a dead end. Working out exact change for 95 cents in quarters and then dimes uses the same pair of operators twice: once on the amount, and once on whatever the quarters left behind.Modulus as a yes-or-no test
So far modulus has answered a how-much question. It also settles a question with only two possible answers: did the division come out exact, or did it not.A leftover of zero is what an exact division looks like from the outside. Nothing else in the arithmetic marks those cases out, so the leftover is the evidence, and a program that wants the yes-or-no has to ask about the leftover rather than about the quotient.
The familiar use of this idea is doing something on only some passes of a loop rather than on every pass. That needs a loop, which arrives later in the course. Here the question stands on its own, answered by an expression whose value is True or False rather than a number.
Walking a longer number
Modulo 10 gives the last digit and floor division by 10 discards it. The same pair works on any power of ten, and that is what lets you reach into the middle of a number instead of stripping it one digit at a time.| Expression | Value when v is 6357 | What it gives |
|---|---|---|
v % 10 | 7 | the last digit |
v % 100 | 57 | the last two digits |
v // 100 | 63 | everything above the last two digits |
v // 1000 | 6 | the leading digit of a four-digit number |
(v // 100) % 10 | 3 | the hundreds digit on its own |