2016-11-19 128 views
-3

我是一名初学者Python学习者,目前我正在研究Luhn Algorithm以检查信用卡验证。我写了大部分的代码,但是我遇到了2个错误,我得到的第一个是num在分配之前被引用。第二个我得到的是'_io.TextIOWrapper'类型的对象没有len()。进一步的帮助/指导将不胜感激。Python信用卡验证

这些是卢恩算法(MOD10校验)

  1. 双从右到左每秒位数的步骤。如果此“加倍”结果为两位数字,请添加两位数字 以获得单个数字。
  2. 现在添加步骤1中的所有单个数字号码。
  3. 在信用卡号码中从右至左添加奇数位置的所有数字。
  4. 总结步骤2的结果& 3.
  5. 如果步骤4的结果可以被10整除,则卡号有效;否则,它是无效的。

这里是我的输出应该是

Card Number   Valid/Invalid 
-------------------------------------- 
3710293    Invalid 
5190990281925290 Invalid 
3716820019271998 Valid 
37168200192719989 Invalid 
8102966371298364 Invalid 
6823119834248189 Valid 

这里是代码。

def checkSecondDigits(num): 
    length = len(num) 
    sum = 0 
    for i in range(length-2,-1,-2): 
     number = eval(num[i]) 
     number = number * 2 
     if number > 9: 
      strNumber = str(number) 
      number = eval(strNumber[0]) + eval(strNumber[1]) 
      sum += number 
     return sum 

def odd_digits(num): 
    length = len(num) 
    sumOdd = 0 
    for i in range(length-1,-1,-2): 
     num += eval(num[i]) 
    return sumOdd 

def c_length(num): 
    length = len(num) 
    if num >= 13 and num <= 16: 
    if num [0] == "4" or num [0] == "5" or num [0] == "6" or (num [0] == "3" and num [1] == "7"): 
     return True 
    else: 
     return False 


def main(): 
    filename = input("What is the name of your input file? ") 
    infile= open(filename,"r") 
    cc = (infile.readline().strip()) 
    print(format("Card Number", "20s"), ("Valid/Invalid")) 
    print("------------------------------------") 
    while cc!= "EXIT": 
     even = checkSecondDigits(num) 
     odd = odd_digits(num) 
     c_len = c_length(num) 
     tot = even + odd 

     if c_len == True and tot % 10 == 0: 
      print(format(cc, "20s"), format("Valid", "20s")) 
     else: 
      print(format(cc, "20s"), format("Invalid", "20s")) 
     num = (infile.readline().strip()) 

main() 
+1

你应该提供回溯,不只是错误信息 –

+0

'甚至= checkSecondDigits(NUM)'...查看这条线。什么是num?这是你的第一个错误 –

+0

回溯(最近通话最后一个): 线58,在 的main() 线48,在主 甚至= checkSecondDigits(NUM) UnboundLocalError:局部变量 'NUM' 分配 –

回答

1

你只是忘了初始化NUM

def main(): 
    filename = input("What is the name of your input file? ") 
    infile= open(filename,"r") 
    # initialize num here 
    num = cc = (infile.readline().strip()) 
    print(format("Card Number", "20s"), ("Valid/Invalid")) 
    print("------------------------------------") 
    while cc!= "EXIT": 
     even = checkSecondDigits(num) 
     odd = odd_digits(num) 
     c_len = c_length(num) 
     tot = even + odd 

     if c_len == True and tot % 10 == 0: 
      print(format(cc, "20s"), format("Valid", "20s")) 
     else: 
      print(format(cc, "20s"), format("Invalid", "20s")) 
     num = cc = (infile.readline().strip()) 
+0

他实际上已经把它初始化到了else之下。 – Onilol

+0

你是一个拯救生命的兄弟。非常感谢你 –

+0

可以将cc重命名为num –