2017-06-05 20 views
2

私のプログラムでは、数値でなければならない入力を取りたいと思います。しかし、ユーザーが文字列を入力した場合、プログラムは例外を返します。プログラムが入力文字列は、例えば.Like「を書いてください停止」プログラムのプリントint型以外のものであるならば、int型とするために変換されますPythonハンドリング例外

x=input("Enter a number") 
     if int(x)=?:   #This line should check whether the integer conversion is possible 
     print("YES") 
     else    #This line should execute if the above conversion couldn't take place 
     print("Stop writing stuff") 

答えて

2

あなたが試す-以外のブロックを使用する必要があります

x=input("Enter a number") 
try: 
    x = int(x) # If the int conversion fails, the program jumps to the exception 
    print("YES") # In that case, this line will not be reached 
except ValueError: 
    print("Stop writing stuff") 
0

try-exceptブロックを使用して例外的なケースをキャッチするだけで、そこにはtatement。このようなもの:

x=input("Enter a number") 
try: 
    x=int(x) 
    print("YES") 
except: 
    print("Stop writing stuff") 
関連する問題