2016-12-29 82 views
0

我想創建一個錯誤陷阱使用try-except catch來防止用戶輸入字符串,但是當我運行代碼時,它不會捕獲錯誤。錯誤陷阱字符串和整數

info=False 
count=input("How many orders would you like to place? ") 
while info == False: 
    try: 
     count*1 
     break 
    except TypeError: 
     print("Please enter a number next time.") 
     quit() 
#code continues   

回答

0

一個更好的辦法來做到這一點是使用一個嘗試except塊

while True: 
    try: 
     count=int(input("How many orders would you like to place? ")) 
     break 
    except: 
     print("This is not a valid input. Try again\n") 

print(count) 
+0

這工作完美。非常感謝你! – TheLegend27

+2

關於此代碼的一條評論。在不指定異常類型的情況下添加一個空的'except:'將會捕獲* every *異常,包括像'KeyboardInterrupt'這樣的系統退出事件(當您點擊'ctrl + c'鍵盤命令時拋出)。改進可能只是通過執行「except Exception:」來捕獲非系統出口異常。 – 2016-12-29 09:45:15

+0

你是對的!感謝您指出,邁克:-) –

0

input返回的值是string

你可以嘗試這樣的事:

try: 
    val = int(userInput) 
except ValueError: 
    print("That's not an int!") 
0

strìnt在python完美的作品:'a'*3 = 'aaa'。您的try區塊不會有異常情況發生。

,如果你想distiguish intstr

try: 
    int(count) 
except ValueError: 
    do_something_else() 

注:這是ValueError而不是TypeError

0

您可以通過以下方式使用TypeError

while True: 
    try: 
     count=input("How many orders would you like to place? ") 
     count += 1 
    except TypeError: 
     print("Please enter a number next time.") 
     break 

需要注意的是,一個字符串可以通過在Python整數相乘,所以我用的加法運算,因爲我們不能在python添加到字符串整數。