2017-06-05 408 views
2

在我的程序中,我想輸入一個應該是數字的輸入。但是,如果用戶輸入字符串,程序會返回一個異常。我希望程序以這樣的方式設置:輸入被轉換成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

你需要使用try-except塊:

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塊來捕捉特殊情況,並在裏面打印您的s tatement。類似這樣的:

x=input("Enter a number") 
try: 
    x=int(x) 
    print("YES") 
except: 
    print("Stop writing stuff")