DEV Community

Cover image for Python Script: Validating Credit Card Number - Luhn's Algorithm
Anurag Rana
Anurag Rana

Posted on • Originally published at pythoncircle.com

Python Script: Validating Credit Card Number - Luhn's Algorithm

This article was originally published at PythonCircle.com.

The Luhn algorithm, also known as the "modulus 10" algorithm, is a checksum formula used to validate a variety of identification numbers, such as credit card numbers, IMEI numbers, National Provider Identifier numbers in the United States, Canadian Social Insurance Numbers, and Israel ID Numbers.

Algorithm:
The formula verifies a number against its included check digit, which is usually appended to a partial account number to generate the full account number.

Generating check digit:

  • Lets assume you have a number as: 3 - 7 - 5 - 6 - 2 - 1 - 9 - 8 - 6 - 7 - X where X is the check digit.
  • Now starting from the rightmost digit i.e. check digit, double every second digit. New number will be: 3 - 14 - 5 - 12 - 2 - 2 - 9 - 16 - 6 - 14 - X
  • Now if double of a digit is more then 9, add the digits. So the number will become: 3 - 5 - 5 - 3 - 2 - 2 - 9 - 7 - 6 - 5 - X
  • Now add all digits. 47 + X
  • Multiply the non-check part by 9. So it will be 47 * 9 = 423
  • The unit digit in the multiplication result is the check digit. X = 3
  • The valid number would be 37562198673.

Validating the generated number:
You can use tools available online to validate that the number generated is valid as per Luhn's algorithm or not. You can validate the number by visiting this site.

Python Script to validate credit card number:

"""
Python script to check the validity of credit card numbers
Author : PythonCircle.Com
Read more : https://www.pythoncircle.com/post/485/python-script-8-validating-credit-card-number-luhns-algorithm/
"""

import sys


def usage():
    msg = """

        usage:
        python3 credit_card_validator credit_card_number

        example:
        python3 credit_card_validator 34678253793

    """
    print(msg)


def get_cc_number():
    if len(sys.argv) < 2:
        usage()
        sys.exit(1)

    return sys.argv[1]


def sum_digits(digit):
    if digit < 10:
        return digit
    else:
        sum = (digit % 10) + (digit // 10)
        return sum


def validate(cc_num):
    # reverse the credit card number
    cc_num = cc_num[::-1]
    # convert to integer list
    cc_num = [int(x) for x in cc_num]
    # double every second digit
    doubled_second_digit_list = list()
    digits = list(enumerate(cc_num, start=1))
    for index, digit in digits:
        if index % 2 == 0:
            doubled_second_digit_list.append(digit * 2)
        else:
            doubled_second_digit_list.append(digit)

    # add the digits if any number is more than 9
    doubled_second_digit_list = [sum_digits(x) for x in doubled_second_digit_list]
    # sum all digits
    sum_of_digits = sum(doubled_second_digit_list)
    # return True or False
    return sum_of_digits % 10 == 0


if __name__ == "__main__":
    print(validate(get_cc_number()))

Code is available on Github.

More from PythonCircle.com:

Discussion (5)

Collapse
lucamuscat profile image
Luca Muscat

That's great! However you can optimize it a little bit and save a couple of lines by keeping the digits variable as a generator since data will be loaded lazily. You may either remove the list function wrapping the enumerate function or you can just move the enumerate function directly into the for loop (removing the need for the digits variable, I'm pretty sure this doesn't hurt readability and keeps the character limit under 80).

Collapse
anuragrana profile image
Anurag Rana Author

Thanks for the suggestions Luca. Will make changes as per your suggestion in next version.

Collapse
markustheuer profile image
markustheuer

The visa card generator creates a credit card by first loading a generator to the personal computer of the user. Then the user makes a choice of which credit card he wants to generate. The computer processes the data and then creates the card. Once the card has been created, the process is done.

Collapse
davidpaine profile image
David Paine

Thanks for sharing. No doubt, due to technological advancement our mode of payment has changed. We shifted from paper currency to digital currency, and credit card is a mode of digital currency. However, there are some cases on the Internet where we need a fake valid card number (dnschecker.org/credit-card-generat...) that must be adequately validated (dnschecker.org/credit-card-validat...) as per the international standards. That usually happens when we download an app or go for its trial version because the Internet is full of scams. And it's better to keep your end safe.

Collapse
isabellgracia profile image
Isabellgracia

hi,
I have checked so many website, your website is very amazing. you should try this
website