Skip to main content
 首页 » 编程设计

python之不确定如何修复此错误 Luhn 算法 PYTHON

2025年04月02日10softidea

好的, 所以我想我快到了 我的第一部分/第二部分单独使用时效果很好,但我无法将两者结合起来 这是我到目前为止所拥有的 我认为错误在最后一点, 抱歉,我是 Python 的新手,所以我希望尽快掌握它

Edit3:我已经让它工作了(在你们的帮助下)但是现在当我输入 3782822463100050 时,它应该是无效的美国运通卡,但它显示为有效的美国运通卡...

Edit1:好的,例如当我发布 0378282246310005(假的美国运通)时它说

Traceback (most recent call last): 
  File "C:/Users/Nat/Desktop/attempt.py", line 39, in <module> 
    print((cardType)+"Valid") 
NameError: name 'cardType' is not defined 

但是当我插入一个像0378282246310005这样的随机数时,它起作用了

请输入您的信用卡号0378282246310005

我们不接受那种卡

Edit2:最后您应该能够输入信用卡号,它会说“您的“信用卡类型”有效(或无效)

或者说“我们不支持这张卡”

#GET number that will be tested 
CreditNumber = input("Please enter your credit card number") 
 
#SET total to 0 
total=0 
 
#LOOP backwards from the last digit to the first, one at a time 
CreditCount = len(CreditNumber) 
for i in range(0, CreditCount, -1): 
    LastDigit=CreditCard[i] 
 
#IF the position of the current digit is even THEN DOUBLE the value of the current digit 
    if i % 2 ==0: 
        LastDigit=LastDigit*2 
 
#IF the doubled value is more than 9 THEN SUM the digits of the doubled value 
        if LastDigit>9: 
            LastDigit=LastDigit/10+LastDigit%10 
 
    total=total + digit 
 
#Figure out what credit card the user has 
if ( CreditNumber[0:2]=="34" or CreditNumber[ 0:2 ] == "37"): 
     cardType = "Your American Express is" 
 
elif ( CreditNumber[ 0 :4 ] =="6011"): 
       cardType = "Your Discover card is" 
 
elif ( CreditNumber[0 :2 ]  in [ "51", "52", "53", "54", "55"]): 
       cardType = "Your Mastercard is" 
 
elif ( CreditNumber == "4" ): 
       cardType = "Your VISA card is" 
 
else: 
       print( "We do not accept that kind of card") 
 
if total % 10 == 0: 
    print((cardType)+"Valid") 
 
else: 
    print((cardType)+"Invalid") 

请您参考如下方法:

在注释#Figure out what credit card the user has下的控制语句中,变量cardType被定义在除else之外的每个分支中>。由于该名称从未在控制语句的范围之外定义,因此当您尝试访问该变量且代码位于 if 语句的 else 分支之后时,解释器会给出一个 NameError。

要解决这个问题,您可以做几件不同的事情。当 CardNumber 无效时,您可以为 cardType 创建一个特殊值,并在下一个控制语句中检查它:

if ...: 
    ... 
else: 
    cardType = "some special value" 
 
if cardType == "some special value": 
    ... 

或者您可以使用 try/except 语句:

try: 
    print(cardType) 
except NameError: 
    print("invalid card number") 

编辑:您还应注意,当前 total 变量将始终为 0,因为 for 循环实际上并未运行。如果你想减少一个范围,第一个参数应该大于第二个,否则范围函数只会创建一个空列表。