2016-12-29 47 views
0

try-exceptキャッチを使用してユーザーが文字列を入力できないようにエラートラップを作成しようとしていますが、コードを実行してもエラーは発生しません。エラートラップ文字列と整数

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

良い方法はあなたが次のようにTypeErrorを使用することができますブロック

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

このコードについてのコメントが1つあります。例外タイプを指定せずに空の 'except:'を追加すると、 'KeyboardInterrupt'(' ctrl + c'キーコマンドを押すとスローされます)のようなシステム終了イベントを含むすべての*例外がキャッチされます。代わりに、例外を除いて 'except except:'を実行することによって、非システム出口例外を捕捉することだけが改善されるかもしれません。 –

+0

あなたは正しいです!マイクを指摘してくれてありがとう:-) –

0

inputの値はです。

あなたはこのような何かを試すことができます:pythonで完璧に動作ìnt

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

str回:'a'*3 = 'aaa'を。あなたのtryブロックで例外は発生しません。

あなたはstrからintをdistiguishする場合:

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

注:それはValueErrorないTypeErrorです。これを行うには

0

以外試みを使用することです。

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で整数倍することができますので、私はほかの操作を使用している、ということに注意してください。