我的程序似乎是作为一个检查数字除了0即使其有效的情况下将返回无效的一切工作?

问题描述:

例如输入0-7487-4459-2将返回有效,它应该但1-841-46202-0返回无效,即使其有效?我真的不知道该怎么做,但我已经测试过,看看11 % 11是什么,它的0,所以0 == 0应该返回True,因此有效?我真的坚持这个我的程序似乎是作为一个检查数字除了0即使其有效的情况下将返回无效的一切工作?

while True: # infinite loop until quit 
answer = input("Enter ISBN or enter q to quit") # enter number 
if answer == "q" or answer == "Q": # quit 
    exit() 
else: 
    isbn = answer 
    temp = "" # temporary 
    answer = "" # set as isbn and reset 'answer' 
    for x in range(len(isbn)): 
     if ord(isbn[x]) == 45: 
      print("", end="") # print nothing when dash 
     else: 
      temp += isbn[x] # add new code to temp 

    isbn = temp # reset temp 
    temp = "" 

    # RUN CHECKS ON ISBN 
    if (len(isbn)) == 10: 
     print("", end="") 
    else: # check length 
     print("Incorrect length for isbn") 
     exit() 

    # CHECK DIGITS 
    if isbn.isdigit() == True: 
     print("", end="") 
    else: 
     print("Non number detected") 
     exit() 

    print(isbn) 
    check = (isbn[len(isbn) - 1]) # add the last digit as check 
    isbn = isbn[:-1] # remove last digit as its check 

    total = 0 
    multi = 10 
    for x in range(len(isbn)): 
     temp = int(isbn[x]) # set it as int 
     total += (temp * multi) # times by multiplier and add to total 
     multi -= 1 # take one 

    answer = (11 - (total % 11)) 
    print(answer) # modulo 11 
    print(check) 
    if int(check) == answer: # check and print valid if valid 

     print("Valid") 
    else: 
     print("Invalid") 

控制台输出:

Enter ISBN or enter q to quit1-841-46202-0 
1841462020 
11 
0 
Invalid 
Enter ISBN or enter q to quit 

answer = (11 - (total % 11))只能产生结果范围为1直通11包容性的,所以没有什么能可能匹配0尝试的校验位answer = -total % 11,当你的原稿给出11时给出0。

两种版本都可以产生10作为答案,它不能匹配一个十进制数字。实际上,ISBN校验位是一个以11为基数的数字,这个额外的可能值被表示为'X'。当答案是10时,您需要添加一个特殊的案例来接受'X' - 否则,您将拒绝大约9%的所有可能的ISBN。

+0

确定感谢虐待给一个去.... –

+0

OK得益于很好的答案都有助于其与X,X和0现在的工作! –

+0

我不能投票tho –

你永远不会执行评估11%11。你为整个数字做了数学运算:总数为%11.这两项中的总数是262和187.你做的计算是从11中减去的。Ah ... jasonharper刚刚发布了那部分。

您经历了很多工作将其余的ISBN转换为数字。你可以摆脱与一个简单的声明:

total = int(isbn[:-1])