DEV Community

Cover image for Python Guide: Credit Card Number Validation Using Luhn's Algorithm
Silver Spades
Silver Spades

Posted on

Python Guide: Credit Card Number Validation Using Luhn's Algorithm

Hey, it's me, Silver, and today we are going to build a simple program that validates credit card numbers using the Luhn algorithm. This is a practical project for anyone learning Python and looking to understand input validation, control flow, and basic algorithm implementation.

What is the Luhn Algorithm?

The Luhn algorithm, also known as the "modulus 10" or "mod 10" algorithm, is a simple checksum formula used to validate various identification numbers, such as credit card numbers. It was created by IBM scientist Hans Peter Luhn and is widely used today.

Let's take an example to ease our trouble:
Consider the test credit card number generated by PayPal: "4032038996592097".

The algorithm works as follows:

  1. Starting from the rightmost digit, double every second digit.Luhn Algo Step 1

  2. If doubling a digit results in a number greater than 9, then add the digits to get a single-digit number (for example, 18: 1 + 8 = 9, 16: 1 + 6 = 7).Luhn Algo Step 2

  3. Now add all the numbers, touched and untouched, at even places and odd places.Luhn Algo Step 3

  4. If the total modulo 10 is equal to 0, the number is valid. We have got 80 here, so our card number is valid.

Let's translate this logic into a simple Python program. You can check out the final results on GitHub too.

Implementing the Luhn Algorithm in Python

Let's dive into the code. Below is a Python script that implements the Luhn algorithm to validate credit card numbers. Additionally, the script ensures that the input is at least a 15-digit number.

Why 15 digits, you say? That's the least number of digits a valid credit card can have. Most credit card companies issue credit cards with 16 digits, but there are some exceptions; for example, American Express issues cards with 15 digits.

Well, let's start.

def main():
    card_number = input("Enter credit card number: ").strip()
    if is_valid_card(card_number):
        print("Valid credit card number.")
    else:
        print("Invalid credit card number.")

def luhn_check(card_number):
    def digits_of(n):
        return [int(d) for d in str(n)]

    digits = digits_of(card_number)
    odd_digits = digits[-1::-2]
    even_digits = digits[-2::-2]
    checksum = sum(odd_digits)

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

    return checksum % 10 == 0

def is_valid_card(card_number):
    if not card_number.isdigit() or len(card_number) < 15:
        return False
    return luhn_check(card_number)

if __name__ == "__main__":
    main()
Enter fullscreen mode Exit fullscreen mode

How It Works

  1. Input Validation: The is_valid_card function checks if the input is a string of at least 15 digits using card_number.isdigit() and len(card_number) >= 15.

  2. Luhn Algorithm: The luhn_check function processes the digits using the Luhn algorithm:

    • It splits the number into individual digits using the internal function digits_of.
    • Then we create two separate lists of even_digits and odd_digits. We perform necessary operations using checksum on both the lists.
    • Finally, we check if the total modulo 10 is 0.
  3. Output: Based on the result of the Luhn check and the length validation, the program prints whether the credit card number is valid or not.

Running the Program

To run the program, follow these steps:

  1. Copy the script into a file named cc-validator.py.
  2. Open a terminal and navigate to the directory containing the script.
  3. Run the script using Python:
python cc-validator.py
Enter fullscreen mode Exit fullscreen mode

Conclusion

Congrats on building your own credit card number validator!

The Luhn algorithm is a powerful tool that showcases how simple mathematical rules can be applied to real-world problems. This project is part of a series of validation projects aimed at helping learners solidify their Python programming skills. You can check out similar validation projects here.

Thanks for reading! Feel free to share your thoughts below.


Footnotes:

Top comments (0)