0

因此,我的任务是验证用户输入的每个 ISBN 10 位数字。我需要确保 1)用户输入不是空白,2)用户输入只是一个整数(我已经完成了),以及 3)他们只输入一位数字。

抱歉,我已经看到了一些类似的问题,但我想保留 try-except 声明(如果可能的话),所以类似的问题并没有太大帮助。

如何验证空白输入并且只输入一位数字?

这是代码:

print("You will be asked to enter an ISBN-10 Number. Please enter it digit by digit.")
ISBN10NumberList = []
ISBN10NumberAdder = 0
for count in range (10):
  validInput1 = True
  if (count <= 8):
    while validInput1 != False:
      try:
        ISBN10NumberList.append(int(input("Please enter the ISBN digit: ")))
        validInput1 = False
      except ValueError:
        print("That is not a valid input! Please enter a integer only.")


  elif (count == 9):
      CheckDigit10 = input("Please enter the ISBN digit: ")
      print("")
      if CheckDigit10 == "X" or CheckDigit10 == "x":
          CheckDigit10 = 10

for count in range (0, 9):
    ISBN10NumberAdder += int(ISBN10NumberList[count]) * (10 - count)

CheckDigit10 = int(CheckDigit10)
CheckingCheckDigit = 11-(ISBN10NumberAdder % 11)

if (CheckDigit10 == CheckingCheckDigit):
    print("This is a valid ISBN!")
else:
    print("This is not a valid ISBN!")
4

1 回答 1

1

所以是的——你让你自己和你的用户的生活变得艰难——这是一个更简单的实现,用户可以一举输入 ISBN。我把一些东西分解成函数,让事情变得更简洁

在主循环中,将反复提示用户输入 ISBN,直到输入有效的 ISBN

def verify_check(isbn_str):
    last = isbn_str[-1] # Last character
    if last == 'X':
        check = 10
    else:
        check = int(last)
    # This part was fine in your original:
    adder = 0
    for count in range(9):
        adder += int(isbn_str[count]) * (10 - count)
    if adder % 11 != check:
         raise ValueError("Checksum failed")

def verify_isbn10(isbn_str):
    if len(isbn_str) != 10:
        raise ValueError("ISBN must be 10 digits long")

    # Check that the first nine chars are digits
    for char in isbn_str[:-1]:
        if not char.isdigit():
            raise ValueError("ISBN must contain digits or X")

    # Special case for the last char
    if not (isbn_str[-1].isdigit or isbn_str[-1] == "X"):
        raise ValueError("ISBN must contain digits or X")
     verify_check(isbn_str)


# Main code:
while 1:
    try:
        isbn_str = raw_input("Enter ISBN: ")
        verify_isbn(isbn_str)
        break
    except ValueError as e:
        print "Whoops:", e
# At this point, isbn_str contains a valid ISBN

如果您想使用 Kevin 的建议并尝试使用正则表达式,您可以使用类似于以下内容的内容替换 verify_isbn10。请注意,它并没有向用户解释到底出了什么问题。

import re
isbn_re = re.compile(r"""
     ^      #Start of string
     [0-9]{9}   # Match exactly 9 digits
     [0-9X]     # Match a digit or X for the check digit
     $            # Match end of string
     """, re.VERBOSE)

def verify_isbn10(isbn_str):
    m = isbn_re.match(isbn_str)
    if m is None:  #User didn't enter a valid ISBN
        raise ValueError("Not a valid ISBN")
    verify_check(isbn_str)
于 2015-02-05T23:51:03.083 回答