The Luhn algorithm or Luhn formula, is a simple formula used to validate a variety of identification numbers, such as credit card numbers. Here is my implementation written in Python:
def checkDigit(digits):
digitList = []
digitOdd = []
checksumOdd = 0
sumOdd = 0
sum_ = 0
sumRounded = 0
difference = 0
#Support for creditcard numbers that are passed in as argument of
#type string or list
if isinstance(digits, str):
for char in digits:
digitList.append(int(char))
elif isinstance(digits, list):
digitList = digits
checkDigit = digitList[len(digitList) -1]
#Remove the checkdigit from the list so we can easily iterate over
#the digitList array without worrying to much about the checkdigit itself
digitList.pop()
#Step 1: Multiplication of all digits in odd index position of digits array
i = 0
for digit in digitList:
if i % 2 == 0:
digitProduct = digitList[i] * 2
digitOdd.append(digitProduct)
i += 1
#Step 2: Built checksums of all products from step 1 and do addition of
#all checksums
for digit in digitOdd:
if digit >= 10:
digit = (digit - 10) + 1
checksumOdd += digit
#Step 3: Addition of all digits in even index position of digits array
i = 0
for digit in digitList:
if i % 2 != 0:
sumOdd += digit
i += 1
#Step 4: Addition of all sums from step 2 and step 3
sum_ = sumOdd + checksumOdd
#Step 5: Round result from step 4 to next largest, through 10 divideable number
sumRounded = int((sum_ / 10) * 10 + 10)
#Step 6: Calculate difference of result from step 5 and step 4
difference = sumRounded - sum_
#Step 7: Check if calculated number is the same as the check digit and
#return either True or False
if difference == checkDigit:
return True
else:
return False
if __name__ == "__main__":
#checkDigit method accepts Lists or Strings as parameter
digitList = [2,7,1,8,2,8,1,8,2,8,4,5,8,5,6,7]
#digitList = "2718281828458566"
if checkDigit(digitList):
print "Creditcard is valid!"
else:
print "Creditcard is not valid!"
This will either return True or False depending if the check digit is valid or not.




#1 by cpio on September 18th, 2009
Quote
Here’s another version:
def luhn( l ):
s, i = 0, 16
while i > 0:
i -= 1
v = ord( l[ 15 - i ] ) – 48 < 9 ):
s += v – 9
else:
s += v
return s % 10 < 1
More details here: http://blogs.media-tips.com/bernard.opic/2009/09/17/algorithme-de-luhn-implementation-python/
#2 by admin on September 18th, 2009
Quote
Hey cpio,
thanks for your comment, your version looks a bit more efficient and way shorter than the one I provided ;)
Regards,
Norman
#3 by Mario Vilas on June 16th, 2010
Quote
There’s a much shorter version of this algorithm in Wikipedia:
http://en.wikipedia.org/wiki/Luhn_algorithm#Implementation_of_standard_Mod_10