Hackerss.com is a community of amazing hackers

Hackerss is a community for developers, data scientitst, ethical hackers, hardware enthusiasts or any person that want to learn / share their knowledge of any aspect of digital technology.

Create account Log in

Posted on

Python Validate credit card numbers

def validate_credit_card_number(card_number):
    Validate the credit card number using the Luhn algorithm.
    # Reverse the credit card number
    card_number = card_number[::-1]
    # Convert to integer
    card_number = [int(x) for x in card_number]
    # Double every second digit
    doubled_second_digit_list = list()
    digits = list(enumerate(card_number, start=1))
    for index, digit in digits:
        if index % 2 == 0:
            doubled_second_digit_list.append(digit * 2)

    # Add the digits if any number is more than 9
    doubled_second_digit_list = [x if x < 10 else x - 9 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

Enter fullscreen mode Exit fullscreen mode

Top comments (0)