使用“is"更好吗?或“=="在 Python 中进行数字比较? [英] Is it better to use "is" or "==" for number comparison in Python?
本文介绍了使用“is"更好吗?或“=="在 Python 中进行数字比较?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 Python 中比较两个数字是使用is"运算符还是=="运算符更好?
示例:
<预><代码>>>>一 = 1>>>是 1真的>>>一个 == 1真的>>>是 0错误的>>>一个 == 0错误的 解决方案
使用 ==
.
有时,在某些 Python 实现中,巧合的是,从 -5 到 256 的整数将与 is
一起使用(例如在 CPython 实现中).但不要依赖于此或在实际程序中使用它.
Is it better to use the "is" operator or the "==" operator to compare two numbers in Python?
Examples:
>>> a = 1
>>> a is 1
True
>>> a == 1
True
>>> a is 0
False
>>> a == 0
False
解决方案
Use ==
.
Sometimes, on some python implementations, by coincidence, integers from -5 to 256 will work with is
(in CPython implementations for instance). But don't rely on this or use it in real programs.
这篇关于使用“is"更好吗?或“=="在 Python 中进行数字比较?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文