Hackerss.com

hackerss
hackerss

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)
        else:
            doubled_second_digit_list.append(digit)

    # 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

print(validate_credit_card_number('4556737586899855'))
Enter fullscreen mode Exit fullscreen mode

Top comments (0)