2

好吧,所以我想我快到了,我的第一/第二部分在他们自己的情况下工作完美,但我无法将两者结合起来这是我到目前为止所拥有的,我认为错误在于最后一点,抱歉,我是 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")
4

1 回答 1

1

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

要解决此问题,您可以做一些不同的事情。cardType您可以为when is invalid创建一个特殊值,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 循环实际上并未运行。如果你想减少一个范围,第一个参数应该大于第二个,否则范围函数只会创建一个空列表。

于 2016-10-17T04:10:18.790 回答