无论如何,是否有使python的错误消息停止中断流程



当我执行下面的代码时,是否有任何方法可以让python编译器运行代码而不会弹出错误消息?

由于我不知道如何区分整数和字符串,
int(result)执行并且result包含字母时,它会吐出一条错误消息,停止程序。

这周围有没有?

这是我的代码:

result = input('Type in your number,type y when finished.n')
int(result)
if isinstance(result,str):
print('finished')

让我们看看你的代码:

int(result)

所有将要做的是在无法转换为int时引发异常result。 它不会改变result. 为什么不呢?因为在python字符串(和int(中,对象不能更改,所以它们是不可变的。 所以:

if isinstance(result,str):
print('finished')

这个测试毫无意义,因为result将永远是一个str,因为你没有改变它 - 这就是input()返回的类型。

处理错误消息的方法是修复或处理它们。 有两种通用方法,"先看后跳"和"异常处理"。 在"跳跃之前先看"中,您将检查是否可以通过使用像str.isdigit()这样的字符串测试将result变成int。 在python中,通常的方法是使用异常处理,例如:

result = input('Type in your number,type y when finished.n')
try:
# convert result to an int - not sure if this is what you want
result = int(result)
except ValueError:
print("result is not an int")
if isinstance(result, int):
print("result is an int")

你可以看到我专门测试了ValueError。 如果您没有这个并且只有except那么它将捕获任何错误,这可能会掩盖其他问题。

实际上,使用Python和许多其他语言,您可以区分类型。

当你执行int(result)时,内置的int假定参数值能够变成整数。如果不是,假设字符串abc123,它不能将该字符串转换为整数,并且会引发异常。

解决此问题的一种简单方法是先检查众多内置isdigit()之一,然后再评估int(result)

# We assume result is always a string, and therefore always has the method `.isdigit`
if result.isdigit():
int(result)
else:
# Choose what happens if it is not of the correct type. Remove this statement if nothing.
pass

请注意,.isdigit()仅适用于整数,10.4将被视为不是整数。无论如何10

我推荐这种方法而不是tryexcept子句,但这也是一个有效的解决方案。

您可以将可能引发错误的所有内容放在 try 块中,并有一个 except 块来保持程序的流程。

顺便说一句,我认为在您的代码中应该是,isinstance(result,int)不是isinstance(result,str)

在您的情况下,

result = input('Type in your number,type y when finished.n')
try:
result = int(result)
except:
pass
if isinstance(result,int):
print('finished')

最新更新