Python implementation of luhn algorithm

The luhn algorithm, or mod 10, was developed by an IBM scientist in the 1950’s. To a large extent it is still used today to validate credit card numbers in front end applications.

If you think back to your high school math classes, mod is simply an infrequently used word for what is sometimes known as the remainder in division. For example a function that takes a numerator and divisor such as mod(10,4) would equal 2, since 10 / 4 would result in a remainder of 2.

Mod 10 simply means the function would look like mod(some number, 10), and the result must = 0.

Since it is mod 10, all you must do is manipulate the last digit to get the check to pass. In other words, if the number is 4359435943594359, you will see the remainder of the check is 4, but needs to be 0. As such, reduce the last 9 to 5 (4359435943594355), and the check will pass.

This is why it is only used to verify a user did not mistype a digit, and not to actually verify a credit card number. Actual card numbers such as VISA normally store business meaningful data in the number, such as digits 2 – 8 representing the bank number, etc.

The full algorithm can be found at wikipedia.org.

Below is is the complete implementation in python.

import sys

card=sys.argv[1]
i = len(card)
cknums = []
while i >= 1:
  tmp = int(card[i - 1]) * 2
  if i % 2 == 1:
    if tmp > 9: 
      cknums.append(int(str(tmp)[0]) +  int(str(tmp)[1]))
    else:
      cknums.append(int(tmp))
  else:
    cknums.append(int(card[i - 1]))
  i = i - 1

j = 0

for i in cknums:
  j = j + i

if j % 10 == 0:
  print "good num"
else:
  print "bad num, change last digit by",j % 10," in either a positive or negative direction (only one will work) to get a valid number"

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.