Recipe 3.15. Checking a Credit Card Checksum
Credit: David Shaw, Miika
Keskinen
Problem
You need to check whether a credit card number respects the industry
standard Luhn checksum algorithm.
Solution
Luhn mod 10 is the credit card
industry's standard for credit card checksums.
It's not built into Python, but
it's easy to roll our own computation for it:
def cardLuhnChecksumIsValid(card_number):
"" checks to make sure that the card passes a luhn mod-10 checksum ""
sum = 0
num_digits = len(card_number)
oddeven = num_digits & 1
for count in range(num_digits):
digit = int(card_number[count])
if not (( count & 1 ) ^ oddeven):
digit = digit * 2
if digit > 9:
digit = digit - 9
sum = sum + digit
return (sum % 10) == 0
Discussion
This recipe was originally written for a now-defunct e-commerce
application to be used within Zope.It can save you time and money to apply this simple validation before
trying to process a bad or miskeyed card with your credit card
vendor, because you won't waste money trying to
authorize a bad card number. The recipe has wider applicability
because many government identification numbers also use the Luhn
(i.e., modulus 10) algorithm.A full suite of credit card validation methods is available at
http://david.theresistance.net//image/library/english/10241_creditValidation.pyIf you're into cool one-liners rather than
simplicity and clarity, (a) you're reading the wrong
book (the Perl Cookbook is a great book that
will make you much happier), (b) meanwhile, to keep you smiling while
you go purchase a more appropriate oeuvre, try:
checksum = lambda a: (
10 - sum([int(y)*[7,3,1][x%3] for x,
y in enumerate(str(a)[::-1])])%10)%10
See Also
A good therapist, if you do prefer the one-line
checksum version.