Skip to main content
 首页 » 编程设计

python之什么时候使用 `>` 和 `!=` 运算符

2025年05月04日11sharpest

在这方面找不到太多。试图比较 2 个值,但它们不能相等。在我的例子中,它们可以(并且经常)大于或小于。

我应该使用:

if a <> b: 
   dostuff 

或

if a != b: 
   dostuff 

This page说它们相似,这意味着它们至少有一些不同之处。

请您参考如下方法:

引自Python language reference ,

The comparison operators <> and != are alternate spellings of the same operator. != is the preferred spelling; <> is obsolescent.

所以,它们是一回事,但是 !=优先于 <> .

我尝试反汇编 Python 2.7.8 中的代码

from dis import dis 
form_1 = compile("'Python' <> 'Python'", "string", 'exec') 
form_2 = compile("'Python' != 'Python'", "string", 'exec') 
dis(form_1) 
dis(form_2) 

得到以下内容

  1           0 LOAD_CONST               0 ('Python') 
              3 LOAD_CONST               0 ('Python') 
              6 COMPARE_OP               3 (!=) 
              9 POP_TOP 
             10 LOAD_CONST               1 (None) 
             13 RETURN_VALUE 
 
  1           0 LOAD_CONST               0 ('Python') 
              3 LOAD_CONST               0 ('Python') 
              6 COMPARE_OP               3 (!=) 
              9 POP_TOP 
             10 LOAD_CONST               1 (None) 
             13 RETURN_VALUE 

两者都是 <>和 !=正在生成相同的字节码

              6 COMPARE_OP               3 (!=) 

所以它们是一体的。

注意事项:

<>根据 the Python 3 Language Reference 在 Python 3.x 中被删除.

引用 official documentation ,

!= can also be written <>, but this is an obsolete usage kept for backwards compatibility only. New code should always use !=.

结论

自 <>在 3.x 中被删除,并且根据文档,!=是首选方式,最好不要使用 <>完全没有。