How to Generate Credit Card Numbers in Python for Testing?

In this tutorial, I will explain how to generate credit card numbers in Python for testing purposes. As a developer, I recently faced this issue while building an online store for my client based in the US. I needed a way to test the checkout process without using real credit cards. After some research, I found that Python provides libraries and techniques to generate credit card numbers for testing. Let us understand some important methods.

Anatomy of Credit Card Numbers

Before we get into the code, it’s helpful to understand the structure of credit card numbers:

  • Credit card numbers are typically 16 digits long (15 for American Express)
  • The first 6 digits represent the Issuer Identification Number (IIN) and identify the card network and bank
  • The 7th-15th digits are the account number
  • The last digit is a checksum used to validate the card number using the Luhn algorithm

The major card networks in the US use the following IIN ranges:

  • Visa: 4xxxxx
  • Mastercard: 51xxxx-55xxxx
  • American Express: 34xxxx, 37xxxx
  • Discover: 6011xx, 65xxxx

Read How to Select Items from a List in Python?

Generate Card Numbers with the Faker Library

The easiest way to generate realistic credit card numbers in Python is by using the Faker library. Faker is a popular Python package that generates fake data for various purposes. It provides functionality to generate valid credit card numbers out of the box.

First, install Faker:

pip install faker

Then import it in your Python code:

from faker import Faker  
fake = Faker()

Now you can generate a credit card number with:

print(fake.credit_card_number()) 

Example output:

4382509903541605

I have executed the above code and added the screenshot below.

Generate Credit Card Numbers in Python

By default, this generates a Visa card number, but you can specify other card types like Mastercard, Amex, or Discover:

print(fake.credit_card_number(card_type='amex')) 

print(fake.credit_card_number(card_type='mastercard'))

Example output:

343663108232670

5453260380017674

I have executed the above code and added the screenshot below.

How to Generate Credit Card Numbers in Python

Faker uses accurate IIN prefixes and generates valid numbers that pass the Luhn check. You can also generate full card details including expiration, name, etc:

print(fake.credit_card_full())

Example output:

VISA 16 digit
Matthew Garcia
4551474586617856 05/34
CVC: 884

I have executed the above code and added the screenshot below.

Generate Credit Card Numbers in Python with the Faker Library

Check out Convert String to List in Python Without Using Split

Generate Card Numbers Manually

If you want more low-level control over the generated numbers, you can write your own Python functions leveraging the Luhn algorithm. This algorithm is used to validate credit card numbers and generate check digits.

Here’s a Python implementation:

import random

def luhn_checksum(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 = 0
    checksum += sum(odd_digits)
    for d in even_digits:
        checksum += sum(digits_of(d*2))
    return checksum % 10
 
def is_luhn_valid(card_number):
    return luhn_checksum(card_number) == 0

def calculate_luhn(partial_card_number):
    check_digit = luhn_checksum(int(partial_card_number) * 10)
    return check_digit if check_digit == 0 else 10 - check_digit

def generate_card(prefix, length):
    
    """
    prefix=IIN, for example "4" for Visa or "51"-"55" for Mastercard
    length=the total number of digits in the card number 
    """
    
    card_number = prefix
    # generate digits
    card_number += "".join([str(random.randint(0,9)) for _ in range(length - len(str(prefix)) - 1)]) 
    
    # calculate check digit
    card_number+=str(calculate_luhn(card_number))
    return card_number

print(generate_card("53", 16))  
# Example output: 5325153879164465

This generates a 16-digit Mastercard number starting with “53”. The calculate_luhn function uses the Luhn algorithm to generate the appropriate check digit. You can modify the prefix and length to generate numbers for different card types.

Read Difference Between = and == in Python

Validate Generated Card Numbers

While the numbers generated by these methods will pass validation checks, they are still fake and cannot be used for real transactions. But you can use them to test your payment forms and checkout process flow.

To validate a card number, use the is_luhn_valid function:

print(is_luhn_valid(5325153879164465))  # True

print(is_luhn_valid(5325153879164464))  # False, invalid check digit

Check out How to Split a Sentence into Words in Python?

Best Practices to Store & Handle Card Data

When dealing with credit card numbers, even fake ones for testing, it’s crucial to follow security best practices:

  • Never store full card numbers in your database or logs. If you need to retain card data, use a secure vault or tokenization service.
  • Do not output full card numbers in responses. Mask all but the last 4 digits.
  • Use HTTPS on all pages that accept or display card numbers.
  • Comply with PCI DSS standards if you process real payment data.

Check out Convert Binary to Decimal in Python

Conclusion

In this tutorial, I have explained to you how to generate valid credit card numbers in Python for testing purposes. I covered the anatomy of credit card numbers, how to generate card numbers with Faker Library, manually and how to validate generated card numbers. We also covered some best practices to store and handle card data.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.