Python处理异常
问题描述:
在我的程序中,我想输入一个应该是数字的输入。但是,如果用户输入字符串,程序会返回一个异常。我希望程序以这样的方式设置:输入被转换成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")
答
你需要使用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")
答
您可以简单地使用try-except块来捕捉特殊情况,并在里面打印您的s tatement。类似这样的:
x=input("Enter a number")
try:
x=int(x)
print("YES")
except:
print("Stop writing stuff")