首页 > 解决方案 > 无论如何使python的错误消息停止破坏流程

问题描述

当我执行下面的代码时,无论如何要让 python 编译器运行代码而不弹出错误消息?

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

有没有办法解决?

这是我的代码:

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

标签: pythonpython-3.x

解决方案


让我们看看你的代码:

int(result)

如果result无法转换为int. 它没有改变result。为什么不?因为在 python 中字符串(和 int)对象不能被改变,所以它们是不可变的。所以:

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

这个测试是没有意义的,因为result永远astr因为你没有改变它——那是 . 返回的类型input()

处理错误消息的方法是修复或处理它们。有两种通用方法,“在你跳跃之前查看”和“异常处理”。在“跳前看”中,您将检查是否result可以int通过使用字符串测试(如str.isdigit(). 在 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那么它会捕获任何错误,这可能会掩盖其他问题。


推荐阅读