2011-12-26 56 views
1

我正在學Python,並且遇到了問題。 遵守本守則:Python 2.7.2如果/或意外的行爲

while 1: 
    print "How many lines do you want to add to this file?" 

    number_of_lines = raw_input(">").strip() 

    if not(number_of_lines.isdigit()) or number_of_lines > 10: 
     print "Please try a number between 1 and 10 inclusive." 
     continue 

代碼詢問用戶的數量,並檢查它的有效性。然而由於某些原因,即使用戶輸入的有效數字小於10,代碼也會顯示錯誤。

我可能在某處發生了一個小錯誤,但我無法弄清楚......是一個python新手!

希望你能幫助!提前致謝。

+0

FYI一般你應該使用'try ... except':口號是EAFP不是LBYL。 – katrielalex 2011-12-27 00:45:05

+0

@katrielalex謝謝,我會在將來考慮這一點,但我還沒有那麼深入。 – Kieran 2011-12-27 13:12:39

回答

5

當從raw_input返回時,您的number_of_lines變量是字符串。你需要將其轉換爲整數與10比較之前:

not(number_of_lines.isdigit()) or int(number_of_lines) > 10 
+0

謝謝,這個解決方案的工作原理正是我所追求的! – Kieran 2011-12-26 22:23:10

3

我會嘗試將字符串轉換爲整數首先,捕獲的錯誤,如果他們把別的東西。這也讓你放棄isdigit電話。像這樣:

while 1: 
    print "How many lines do you want to add to this file?" 

    try: 
     number_of_lines = int(raw_input(">").strip()) 
    except ValueError: 
     print "Please input a valid number." 
     continue 

    if number_of_lines > 10: 
     print "Please try a number between 1 and 10 inclusive." 
     continue 
+0

謝謝你的回答。我將在下一次考慮這一點,但我想避免使用try/except,因爲我仍然是一個新手,還沒有那麼遠!儘管我已經提出了你的答案。 – Kieran 2011-12-26 22:24:13