在我的程序中,我想接受一个应该是数字的输入。但是,如果用户输入一个字符串,程序会返回一个异常。我希望程序设置为将输入转换为int,然后如果字符串不是 int,则程序会打印“请停止写入”。例如:
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 block :
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")
