Skip to main content
 首页 » 编程设计

python之Luhn 的算法伪代码代码

2025年04月02日9开发

大家好,我是编程界的新手。对于学校练习题,我得到了以下文本,我想将其转换为代码。我已经花了几个小时在上面,但似乎仍然无法弄清楚,但我决心学习这个。我目前遇到错误

  line 7, in <module> if i % 2 == 0: TypeError: not all arguments converted during string formatting  

这是什么意思?我还在学习循环,我不确定它的格式是否正确。谢谢你的时间。

# GET user's credit card number 
# SET total to 0 
# LOOP backwards from the last digit to the first one at a time 
    # IF the position of the current digit is even THEN 
        # DOUBLE the value of the current digit 
        # IF the doubled value is more than 9 THEN 
            # SUM the digits of the doubled value 
        # ENDIF 
       # SUM the calculated value and the total 
    # ELSE 
        # SUM the current digit and the total 
    # ENDIF 
# END loop 
# IF total % 10 == 0 THEN 
    # SHOW Number is valid 
# ELSE 
    # SHOW number is invalid 
# ENDIF 
 
 
creditCard = input("What is your creditcard?") 
total = 0 
for i in creditCard[-1]: 
    if i % 2 == 0: 
        i = i * 2 
        if i > 9: 
            i += i 
    total = total + i 
 
    else: 
        total = total + i 
 
if total % 10 == 0: 
    print("Valid") 
 
else: 
    print("Invalid") 

请您参考如下方法:

好吧,我可以看到 2 个问题:

1)当你这样做的时候:

for i in creditCard[-1] 

您无需对信用卡进行迭代,您只需取最后一位数字即可。 你可能打算做

for i in creditCard[::-1] 

这会将数字从最后一个迭代到第一个

2) 伪代码说,如果它的 POSITION 是偶数,则将数字加倍,而不是数字本身是偶数

所以你可以这样做:

digit_count = len(creditCard) 
for i in range(digit_count -1, -1, -1): 
    digit = creditCard[i] 

或者看看enumerate内置函数

编辑:

完整示例:

creditCard = input("What is your creditcard?") 
total = 0 
digit_count = len(creditCard) 
for i in range(0, digit_count, -1): 
    digit = creditCard[i] 
 
    if i % 2 == 0: 
        digit = digit  * 2 
        if digit  > 9: 
            digit = digit / 10 + digit % 10 # also noticed you didnt sum the digits of the number   
 
    total = total + digit 
 
 
 
if total % 10 == 0: 
    print("Valid") 
 
else: 
    print("Invalid")