2015-02-05 241 views
0

所以,我的任務是驗證用戶輸入的每個他們輸入的ISBN 10數字。我需要確保1)用戶輸入不是空白,2)用戶輸入只是一個整數(我已經完成),3)他們只輸入一個數字。ISBN檢查器 - 驗證用戶輸入

對不起,我已經看到了一些類似的問題,但我想保留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!") 
+3

按位數輸入?這是什麼模式,由Sadism編程? – 2015-02-05 21:43:42

+0

哈哈哈,好點。 – electricbl00 2015-02-05 21:45:45

+0

Ignacio有一個很好的觀點。爲什麼不把整個輸入(作爲一個字符串),通過char遍歷它來做你的理智檢查,然後在最後執行有效性檢查? – MattDMo 2015-02-05 21:51:49

回答

1

所以,是的 - 你正在生活困難爲你和你的用戶 - 這裏是一個簡單的實現,用戶可以一舉進入國際標準書號。我分解了一些東西進入功能,使事情變得更清潔

在主循環中,用戶將被反覆提示的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 

如果你想用凱文建議並嘗試使用正則表達式,您可以使用類似以下替代方式的內容作爲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)