2014-04-29 35 views
0

我正在製作ISBN校驗碼數字程序。但是,儘管我已經制作了我的程序,以便它只接受長度爲10的值,但如果輸入10個字母,它將會崩潰。您如何要求輸入驗證爲10位數的整數?

有誰知道如何解決這個問題?

我的代碼:

isbnnumber = input('Please input your 10 digit book no. : ') 
while len(isbnnumber) != 10: 
    print('You have not entered a 10 digit value! Please try again.') 
    isbnnumber = input('Please input your 10 digit book no. : ') 
else: 
    no1 = int(isbnnumber[0])*11 
    no2 = int(isbnnumber[1])*10... etc... 

幫助將非常感謝,謝謝。

+0

你使用Python 3.x嗎?如果是這樣,你應該用'Python-3.x'來標記它 – Matthew

+0

是的,我會做。有任何問題的幫助? – user3576688

+0

許多ISBN都包含字母X以及數字,任何字符限制都不會在這些ISBN上出現。大寫字母X表示用作校驗數字時的數字10 http://www.isbn.org/faqs_general_questions#isbn_faq5 – Mousey

回答

3

您可以使用str.isdigit來測試一個字符串是否是所有的數字:

while len(isbnnumber) != 10 or not isbnnumber.isdigit(): 

請參見下面的演示:

>>> '123'.isdigit() 
True 
>>> '123a'.isdigit() 
False 
>>> 
>>> 
>>> isbnnumber = input('Please input your 10 digit book no. : ') 
Please input your 10 digit book no. : 123 
>>> while len(isbnnumber) != 10 or not isbnnumber.isdigit(): 
...  print('You have not entered a 10 digit value! Please try again.') 
...  isbnnumber = input('Please input your 10 digit book no. : ') 
... 
You have not entered a 10 digit value! Please try again. 
Please input your 10 digit book no. : 123456789 
You have not entered a 10 digit value! Please try again. 
Please input your 10 digit book no. : 123456789a 
You have not entered a 10 digit value! Please try again. 
Please input your 10 digit book no. : 1234567890 
>>> 
+0

我怎麼說不是數字?這是非常有用的,但我需要相反的方式來適應我的程序。 – user3576688

+0

@ user3576688它的確如此。它基本上是這樣說的:'循環直到字符串長度爲10個字符並且包含所有數字' – Matthew

+0

大寫字母X可以用作ISBN中的校驗數字,OP沒有提到http://www.isbn.org/faqs_general_questions# isbn_faq5 – Mousey

0

您可以用更豐富的一個替代while循環的條件檢查數字,例如:

while not isbnnumber.isdigit() or len(isbnnumber) != 10:  
1

請注意,不僅有ISBN-10 ,還有ISBN-13(實際上更常用於全球)。 此外,ISBN-10不一定都是全部數字:一個數字是一個校驗和,它可以評估爲字母「X」(當它改爲10時,數字)。 當你在它的時候:檢查那些校驗和數字;他們在那裏是有原因的。

所以我建議你做一些輔助功能:

def is_valid_isbn(isbn): 
    return is_valid_isbn10(isbn) or is_valid_isbn13(isbn) 

def is_valid_isbn10(isbn): 
    # left as an exercise 
    return len(...) and isbn10_validate_checksum(isbn) 

def is_valid_isbn13(isbn): 
    # left as an exercise 
    return len(...) and isbn13_validate_checksum(isbn) 

和實現輸入迴路如下:

valid_isbn=False 
while not valid_isbn: 
    isbn = input('Please input your ISBN: ') 
    valid_isbn = is_valid_isbn(isbn) and isbn # and part is optional, little trick to save your isbn directly into the valid_isbn variable when valid, for later use. 
+0

upvoting在處理大寫字母X時用作checkdigit http://www.isbn.org/faqs_general_questions#isbn_faq5 – Mousey

0

隨着regular expressions,您可以準確測試給定的字符串定義的格式。

import re 

m = re.match(r'^\d{10}$', isbn) 
if m: 
    # we have 10 digits! 

這裏的正則表達式是\d{10}\d的意思是,你正在尋找一個數字,{10}的意思是,你需要正好10個數字。該^標記字符串的開始和$字符串的結尾。

使用正則表達式並不總是您需要的,如果您第一次使用正則表達式,則需要一些時間來理解。但是正則表達式是開發最強大的工具之一。