December 22, 2024

Credit Card Number Validator using Luhn Algorithm

Credit Card Validator using Luhn Algorithm
Credit Card Number Validator using Python and Luhn Algorithm

Using Python and Luhn Algorithm

The purpose of this article is to explain how to write a simple credit card validator using Python and the Luhn algorithm. Before we get into the code, lets discuss some background information about the Algorithm.

About Luhn Algorithm

Hans Peter Luhn
Hans Peter Luhn
(July 1, 1896 – August 19, 1964)

In 1954, German computer scientist Hans Peter Luhn (seen on the left), developed the Luhn algorithm. Luhn was a researcher in the field of computer science and Library & Information Science for IBM. Th algorithm also known as the “modulus 10 algorithm,” is a check sum formula used to validate a variety of identification numbers including credit card numbers.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. It is not intended to be a cryptographically secure hash function; instead, it was created to detect accidental errors rather than defend against malicious attacks.

How the Algorithm Works

  1. The Luhn algorithm starts from the last digit which is called the check digit. Then moving from left to right (immediately left of the check digit), double the value of every digit at even indices.
  2. If the result of this doubling operation is greater than 9 (e.g., 6 × 2 = 12), then subtract 9 from the result (e.g., 12: 12 − 9 = 3) or, equivalently, add the digits of the result (e.g., 12: 1 + 2 =3).
  3. Now sum all the digits (including the check digit).
  4. If the total is divisible by 10 then the number is valid; otherwise, it is not valid.

Implementing Luhn Algorithm using Python

The solution below will take a string argument called ‘credit_number‘ which represent the credit card number that will be verified. The pseudo-code below will help explain the steps taken for each line of code.

Pseudo-code

  1. Change string to list datatype
  2. Remove last digit (check digit)
  3. Reverse remaining digits
  4. Double digits at even indices
  5. Subtract 9 if over 9
  6. Add the check digit back to the list
  7. Sum all digits
  8. If the sum is divisible by 10 then it is valid; otherwise, Invalid
def validate_credit_card(card_number: str) -> bool:
    """This function validates a credit card number."""
    # 1. Change datatype to list[int]
    card_number = [int(num) for num in card_number]

    # 2. Remove the last digit:
    checkDigit = card_number.pop(-1)

    # 3. Reverse the remaining digits:
    card_number.reverse()

    # 4. Double digits at even indices
    card_number = [num * 2 if idx % 2 == 0
                   else num for idx, num in enumerate(card_number)]

    # 5. Subtract 9 at even indices if digit is over 9
    # (or you can add the digits)
    card_number = [num - 9 if idx % 2 == 0 and num >= 9
                   else num for idx, num in enumerate(card_number)]

    # 6. Add the checkDigit back to the list:
    card_number.append(checkDigit)

    # 7. Sum all digits:
    checkSum = sum(card_number)

    # 8. If checkSum is divisible by 10, it is valid.
    return checkSum % 10 == 0


if __name__ == '__main__':
    # American Express
    print(validate_credit_card('378282246310005'))  # True
    print(validate_credit_card('371449635398431'))  # True
    # American Express Corporate
    print(validate_credit_card('378734493671000'))  # True
    # Australian BankCard
    print(validate_credit_card('5610591081018250'))  # True
    # Diners Club
    print(validate_credit_card('30569309025904'))  # True
    print(validate_credit_card('38520000023237'))  # True
    # Discover
    print(validate_credit_card('6011111111111117'))  # True
    print(validate_credit_card('6011000990139424'))  # True
    # MasterCard
    print(validate_credit_card('5555555555554444'))  # True
    print(validate_credit_card('5105105105105100'))  # True
    # Visa
    print(validate_credit_card('4111111111111111'))  # True
    print(validate_credit_card('4012888888881881'))  # True

    # Invalid Credit Card Number
    print(validate_credit_card('7762888103111881'))  # False
    print(validate_credit_card('37612555227841800'))  # False

This Code available at GitHub. This is one solution on how to implement a simple credit card validator using Python. You can check the validity of the number using with this credit card validator.

Conclusion

This article discussed how to utilize the Luhn Algorithm and Python to validate credit card numbers. Hopefully you have a better understanding on how the algorithm works, and can write your own credit card number validator using Python. If not, there are available Python libraries that can be downloaded which would make it easier to include Luhn-based identification number verification in software applications.

If you found this article helpful or have any questions, please leave a comment.

Leave a Reply

Your email address will not be published.