2014-11-01 57 views
1

我正在python 3中編寫代碼,我需要根據輸入的內容輸出兩個不同的字符串輸出。 它們都是ValueErrors。如何捕捉兩種不同類型的錯誤輸入

try: 
    number = False 
    while number == False: 
     chooseword = int(input("Please enter an integer number (0<=number<10) to choose the word in the list: ")) 

except ValueError: #empty input 
    print("Empty input!") 
except ValueError: #non-integer, non-empty input 
    print("Input must be an integer!") 
else: #do stuff 

我試過了這個問題的方法,但我只得到一個打印的消息。 How to catch empty user input using a try and except in python?

我也試圖通過使用while循環,並試圖趕上其他選擇與除塊嘗試從兩個選項中的一個忽略一個ValueError:

empty = True 
while empty == True: 
    chooseword = int(input("Please enter an integer number (0<=number<10) to choose the word in the list: ")) 
    if chooseword = "": 
     empty = True 
+1

'if chooseword =「」:'是一個語法錯誤(單個'=',這在if語句中是非法的)。 – Carpetsmoker 2014-11-01 18:29:29

回答

2

由於您正在捕捉ValueError,所以第一個except將始終抓住它。事實上,如果你看一下ValueErrorint()加薪,這是同樣的在兩種情況下:

>>> int('') 
ValueError: invalid literal for int() with base 10: '' 
>>> int('1.2') 
ValueError: invalid literal for int() with base 10: '1.2' 

如果要特意趕空的情況下,只要看看例外:

try: 
    word = input("Please enter an integer number (0<=number<10) to choose the word in the list: ") 
    word = int(word) 
except ValueError as e: 
    if not word: 
    print("Empty!") 
    else: 
    print("Invalid!") 
+0

謝謝!我一直在四處尋找可以工作的東西,而且我嘗試了這一點,但是我錯過了在輸入的不同步驟中使用int(單詞)! – 2014-11-01 19:11:55

1

拆分兩個錯誤條件使得每個被單獨處理:

number = None 
while number is None: 
    chooseword = input("Please enter an integer number (0<=number<10) to choose the word in the list: ") 
    if not chooseword.strip(): 
     print("Empty input!") 
    else: 
     try: 
      number = int(chooseword) 
     except ValueError: 
      print("Input must be an integer!") 

在這種情況下,將chooseword.strip()從輸入刪除任何空白字符,從而使空或全部空間輸入被作爲零長度字符串處理。如果提供輸入,則try/except塊將捕獲任何非整數值。

0

爲值誤差被別人解釋,你也可以通過這種方法

while True: 
    answer = input('Enter a number: ') 
    if isinstance(answer,int) and answer in range(0,10): 
     do_what_you want() 
     break 
    else: 
     print "wrong Input" 
     continue 

print answer 

instance方法將檢查輸入做相同的是int或不,isinstance將返回True,如果它的int其他False。如果a在0-9之間,則範圍內的回答將返回,否則返回false。

0

可以改革蟒蛇輸入函數是這樣的:

請定義一個新的功能,像

def Input(Message): 

設置像

Value = None 

一個初始值,直到輸入的值是不是號碼,嘗試獲得號碼

while Value == None or Value.isdigit() == False: 

控制I/O錯誤等

try: 
    Value = str(input(Message)).strip() 
except InputError: 
    Value = None 

最後,你可以回到你的價值,它的可無或真值。