python通过Luhn算法验证信用卡卡号是否有效

2022-03-11 00:00:00 算法 卡号 信用卡

python通过Luhn算法验证信用卡卡号是否有效

"""
皮蛋编程(https://www.pidancode.com)
创建日期:2022/3/28
功能描述:python通过Luhn算法验证信用卡卡号是否有效
"""
def cardLuhnChecksumIsValid(card_number):
    """ checks to make sure that the card passes a luhn mod-10 checksum """
    sum = 0
    num_digits = len(card_number)
    oddeven = num_digits & 1
    for count in range(0, num_digits):
        digit = int(card_number[count])
        if not (( count & 1 ) ^ oddeven ):
            digit = digit * 2
        if digit > 9:
            digit = digit - 9
        sum = sum + digit
    return ( (sum % 10) == 0 )


print(cardLuhnChecksumIsValid('543298376'))

输出:True

相关文章