不知道如何修复此错误Luhn算法PYTHON

时间:2016-10-17 03:55:43

标签: python luhn

好的, 所以我想我差不多了, 我的第一部分/第二部分在他们独立时工作得很完美,但我在将两者结合起来时遇到了麻烦 这就是我到目前为止所拥有的 我认为错误是最后一点, 对不起,我是python的新手,所以我希望尽快掌握它

编辑3:我已经让它工作了(在你们的帮助下)但现在当我输入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:最后你应该可以输入一个信用卡号码,然后它会说&#34;你的信用卡类型&#34;有效(或无效)

或者说&#34;我们不支持这张卡&#34;

#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")

1 个答案:

答案 0 :(得分:1)

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

要解决此问题,您可以执行几项不同的操作。当cardType无效时,您可以为CardNumber创建一个特殊值,并在下一个控制语句中检查它:

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循环实际上并未运行。如果要减小范围,第一个参数应该大于第二个参数,或者范围函数只会创建一个空列表。