How does the machine know?
You type your card number into a website. You get one digit wrong. The site says the number is not valid before it asks the bank anything.
It did a quick sum with the digits. One digit of the number is there to make that sum work.
Key words
| Word | What it means | Example |
|---|---|---|
| Check digit | An extra digit worked out from the other digits. It is used to find mistakes. | the last digit of an account number |
| Algorithm | A set of steps to follow to do a job. | |
| Remainder | What is left over after dividing. | 89 divided by 10 leaves 9 |
| Modulus | The Python sign % that gives the remainder. | 89 % 10 is 9 |
| Validation | A check that data is correct and makes sense. | |
| Digit | One of the symbols 0 to 9. |
The cells students fill in are left blank in this preview.
The idea
A check digit is added to the end of a code, such as an account number. It is worked out from the other digits by an algorithm.
When somebody types the code, the computer works the digit out again. If the two digits are different, the code has a mistake. This is a kind of validation.
Real systems use many different algorithms. You do not need to learn any of them. If a question needs one, it gives you the steps.
Try it: the remainder
print(89 % 10)
print(17 % 5)
print(20 % 10)
print(7 % 10)
# % gives what is left after dividing.
# 89 divided by 10 is 8 with 9 left over.
# Change the numbers and predict the answer first.
Worked example: one simple algorithm
| Step | Code 245 | Code 123 |
|---|---|---|
| Add the digits | 2 + 4 + 5 = 11 | 1 + 2 + 3 = 6 |
| How far to the next ten? | 20 - 11 = 9 | 10 - 6 = 4 |
| The check digit is | 9 | 4 |
| The full code is | 2459 | 1234 |
| Check: add all four digits | 2 + 4 + 5 + 9 = 20 | 1 + 2 + 3 + 4 = 10 |
The cells students fill in are left blank in this preview.
No check finds every mistake
Take the code 1234. Somebody types 1324. The 2 and the 3 swapped places. The digits still add up to 10. This simple rule does not find that mistake.
Real systems use cleverer rules. The idea is the same: work the digit out again, then compare.
Try it: check a code
code = "2459"
digits = code[:-1]
last = int(code[-1])
total = 0
for letter in digits:
total = total + int(letter)
# The extra % 10 makes a remainder of 0 give a check digit of 0.
check = (10 - total % 10) % 10
print("Check digit should be:", check)
if check == last:
print("The code is valid.")
else:
print("The code has a mistake.")
# Change the last digit of the code and run it again.
When the remainder is 0
data-callouts.warning.label
If the total already ends in 0, the remainder is 0. Then the check digit is 0, not 10. A check digit is one digit only.
Quick check: the arithmetic
Have a go
Quick check: the arithmetic
4 questionsYour answers are marked here and are not kept. A college account keeps every student’s marks.