python - 无论如何使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)
如果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
那么它会捕获任何错误,这可能会掩盖其他问题。
推荐阅读
- performance - 系统鼠标的移动速度有多快?
- android - Meteor 构建失败:“Android 目标:android:命令失败,退出代码 ENOENT”
- css - 在 react-native 中将阴影应用于容器
- xcode - iOS 12 iPad 拒绝启动请求 - Xcode
- git - 如何获取 ./configure 以生成默认值
- xcode - Xamarin.ios 无法直接部署到物理设备
- entity-framework - 使用带有 ASP.NET 样板的测试框架“努力”时出现问题
- munin - 你如何让 munin 停止发送智能退出状态的警报?
- angular - 使用 Angular 6 在后台进行多个 http 请求
- ionic-framework - 进行构建时在 ionic 中动态设置变量