Learning Scientific Programming with Python (2nd edition)
P2.5.3: The Luhn algorithm
Question P2.5.3
The Luhn algorithm is a simple checksum formula used to validate credit card and bank account numbers. It is designed to prevent common errors in transcribing the number, and detects all single digit errors and almost all transpositions of two adjacent digits. The algorithm may be written as the following steps:
- Reverse the number;
- Treating the number as an array of digits, take the even-indexed digits (where the indices start at 1) and double their values. If a doubled digit results in a number greater than 10, add the two digits (e.g. the digit 6 becomes 12 and hence 1 + 2 = 3);
- Sum this modified array;
- If the sum of the array modulo 10 is 0 the credit card number is valid.
Write a Python program to take a credit card number as a string of digits (possibly in groups, separated by spaces) and establish if it is valid or not. For example, the string '4799 2739 8713 6272'
is a valid credit card number but any number with a single digit in this string changed is not.