 Credit card number validation using Luhn’s algorithm in python

In this blog post, we shall how to validate a credit card number using Luhn’s algorithm. We shall also learn about Luhn’s algorithm where and how it is used. This blog post also contains a sample python code to validate the credit card number.

Luhn’s algorithm

The Luhn algorithm or Luhn formula, also known as the “modulus 10” or “mod 10” algorithm, named after its creator, IBM scientist Hans Peter Luhn, is a simple checksum formula used to validate a variety of identification numbers, such as credit card numbers, IMEI numbers, National Provider Identifier numbers, etc.

The algorithm is in the public domain and is in wide use today. It is specified in ISO/IEC 7812–1. It is not intended to be a cryptographically secure hash function; it was designed to protect against accidental errors, not malicious attacks. Most credit cards and many government identification numbers use the algorithm as a simple method of distinguishing valid numbers from mistyped or otherwise incorrect numbers.

How does it work?

Luhn’s algorithm consists of the following three steps. They are,

1. Starting from the rightmost digit, double every second digit.

2. If the result is greater than 10, i,e if the result is a two-digit number add the individual digits to make it a single digit. In the above example, we have 4 two-digit numbers such as 10, 18, 18, and 18. Add the individual digits to make it 1, 9, 9, and 9.

3. Add all the digits together and find the sum. If the modulus of the sum is 0 or in other words if the sum is a multiple of 10, the credit card number is valid.

Python Implementation

Let us implement the above algorithm in python. I will break down the code into small parts. The steps are,

1. Get the card number as a list of numbers.
def digits_of(n):
return [int(d) for d in str(n)]
digits = digits_of("4532015112830366")

2. Get a list of odd and even digits starting from the rightmost or last digit.

odd_digits = digits[-1::-2]
even_digits = digits[-2::-2]

3. Multiply each value from the even_digits by 2. If any number is greater than 9, sum its digits to convert it into a single-digit number. Here we are converting all the numbers to a list of individual digits and summing it up.

checksum = 0
for d in even_digits:
checksum += sum(digits_of(d*2))

4. Sum all the odd numbers along with this checksum.

checksum += sum(odd_digits)

5. If the modulus of the checksum is 0, then the number is valid.

print("valid") if checksum%90==0 else print("Invalid")

Putting it all together our code will look like this.

Conclusion 