验证信用卡

  • Have you ever wondered how websites validate your credit card number when you shop online? They don’t check a massive database of numbers, and they don’t use magic. In fact, most credit providers rely on a checksum formula for distinguishing valid numbers from random collection of digits (or typing mistakes).

    In this lab, you will implement a validation algorithm for credit cards. The algorithm follows these steps:

    • Double the value of every second digit beginning with the rightmost.
    • Add the digits of the doubled values and the undoubled digits from the original number.
    • Calculate the modulus of the sum divided by 10.
If the result equals 0, then the number is valid.
下面是代码:
def is_valid(a):
    sum = 0
    if len(a)%2==0:#判断信用卡位数,偶数位
        for i in range(0,len(a)):#遍历所有
            if i % 2 == 0:#需要*2的位数
               
           
                a_10 =(int(a[i])*2)//10#十位,若无则为0
                a_1 = (int(a[i])*2)%10#个位
           
                sum +=(a_10+a_1)#求和
               
            else:
                sum +=int(a[i])#不需要*2的位数求和
               
           
    else :#信用卡位数,奇数位
        if len(a)%2!=0:
            for i in range(0,len(a)):
                if i % 2 != 0:
               
           
                    a_10 =(int(a[i])*2)//10
                    a_1 = (int(a[i])*2)%10
           
                    sum +=(a_10+a_1)
               
                else:
                    sum +=int(a[i])
    if sum%10==0:
        print('是信用卡')
    else:
        print('不是信用卡')
               
a = input('输入卡号:')   
is_valid(a)

你可能感兴趣的:(验证信用卡)