且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Python 3.2中检查整数?

更新时间:2023-11-28 15:01:40

这里***的选择是o抓住例外。出了问题,这就是设计要处理的异常:

The best option here is to catch the exception. Something has gone wrong, and that's exactly what exceptions are designed to handle:

try:
    ...
except ValueError:
    print("You need to enter an integer!")
    ...

Python有的口头禅请求宽恕而不是权限,所以不要事先检查它是否有效,尝试一下,如果没有,请处理问题工作。

Python has the mantra of it's better to ask for forgiveness than permission, so don't check if it works beforehand, try it, then handle the problem if it doesn't work.

这样可以获得更可靠的代码(检查可能会意外地禁止输入良好的输入,或者通过错误的输入),并使代码读取更好(首先处理正常情况) ,然后处理问题,而不是检查问题,然后处理)。

This makes for more reliable code (the check might accidentally disallow good input, or let through bad input), and makes code read better (you deal with the normal case first, then handle problems, rather than having to check for problems, then process).