Python 中有“不等于”运算符吗?

问题描述 投票:0回答:10

“不等于”怎么说?

if hi == hi:
    print "hi"
elif hi (does not equal) bye:
    print "no hi"

有没有类似

==
的意思是“不等于”?

python comparison operators comparison-operators
10个回答
680
投票

使用

!=
。请参阅比较运算符。为了比较对象身份,您可以使用关键字
is
及其否定
is not
.

例如

1 == 1 #  -> True
1 != 1 #  -> False
[] is [] #-> False (distinct objects)
a = b = []; a is b # -> True (same object)

70
投票

不等于

!=
(对比等于
==

你在问这样的事情吗?

answer = 'hi'

if answer == 'hi':     # equal
   print "hi"
elif answer != 'hi':   # not equal
   print "no hi"

这个 Python - 基本运算符 图表可能会有帮助。


32
投票

!=
(不等于)运算符,当两个值不同时返回
True
,但要小心类型,因为
"1" != 1
。这将始终返回 True,
"1" == 1
将始终返回 False,因为类型不同。 Python 是动态的,但是是强类型的,而其他静态类型的语言会抱怨比较不同的类型。

还有

else
条款:

# This will always print either "hi" or "no hi" unless something unforeseen happens.
if hi == "hi":     # The variable hi is being compared to the string "hi", strings are immutable in Python, so you could use the 'is' operator.
    print "hi"     # If indeed it is the string "hi" then print "hi"
else:              # hi and "hi" are not the same
    print "no hi"

is
运算符是 object identity 运算符,用于检查两个对象实际上是否相同:

a = [1, 2]
b = [1, 2]
print a == b # This will print True since they have the same values
print a is b # This will print False since they are different objects.

13
投票

您可以同时使用

!=
<>

但是,请注意,在不推荐使用

!=
的情况下,首选
<>


7
投票

看到其他人已经列出了大多数其他表示不等于的方式,我将添加:

if not (1) == (1): # This will eval true then false
    # (ie: 1 == 1 is true but the opposite(not) is false)
    print "the world is ending" # This will only run on a if true
elif (1+1) != (2): #second if
    print "the world is ending"
    # This will only run if the first if is false and the second if is true
else: # this will only run if the if both if's are false
    print "you are good for another day"

在这种情况下,很容易将正 == (true) 的检查切换为负,反之亦然...


0
投票

对于“不等于”条件,Python 中有两个运算符 -

a.) != 如果两个操作数的值不相等,则条件为真。 (a != b) 是真的。

b.) <> 如果两个操作数的值不相等,则条件为真。 (a <> b) 是真的。这类似于 != 运算符。


0
投票

你可以用“is not”表示“不等于”或“!=”。请看下面的例子:

a = 2
if a == 2:
   print("true")
else:
   print("false")

上面的代码将打印“true”作为在“if”条件之前赋值的 a = 2。现在请看下面的代码“不等于”

a = 2
if a is not 3:
   print("not equal")
else:
   print("equal")

上面的代码将打印“不等于”作为 a = 2 如前所述。


0
投票

您可以使用

!=
运算符来检查不等式。

此外,在 Python 2 中有

<>
运算符,它曾经做同样的事情,但在 Python 3 中已被 deprecated


0
投票

标准

operator
模块包含
ne
方法,它是
!=
a.k.a. 不等于运算符的包装器。

import operator
operator.ne(1, 1)   # False
operator.ne(1, 3)   # True

如果您需要在预期功能的设置中进行比较,这将特别有用。

a = [1, 2, 3, 4]
b = [2, 2, 3, 3]
list(map(operator.ne, a, b))  # [True, False, False, True]

-2
投票

使用

!=
<>
。两者都代表不相等。

比较运算符

<>
!=
是同一运算符的不同拼写。
!=
是首选拼写;
<>
已过时。 (参考:Python语言参考)

© www.soinside.com 2019 - 2024. All rights reserved.