“不等于”怎么说?
if hi == hi:
print "hi"
elif hi (does not equal) bye:
print "no hi"
有没有类似
==
的意思是“不等于”?
使用
!=
。请参阅比较运算符。为了比较对象身份,您可以使用关键字is
及其否定is not
.
例如
1 == 1 # -> True
1 != 1 # -> False
[] is [] #-> False (distinct objects)
a = b = []; a is b # -> True (same object)
不等于
!=
(对比等于==
)
你在问这样的事情吗?
answer = 'hi'
if answer == 'hi': # equal
print "hi"
elif answer != 'hi': # not equal
print "no hi"
这个 Python - 基本运算符 图表可能会有帮助。
有
!=
(不等于)运算符,当两个值不同时返回 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.
您可以同时使用
!=
或<>
。
但是,请注意,在不推荐使用
!=
的情况下,首选 <>
。
看到其他人已经列出了大多数其他表示不等于的方式,我将添加:
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) 的检查切换为负,反之亦然...
对于“不等于”条件,Python 中有两个运算符 -
a.) != 如果两个操作数的值不相等,则条件为真。 (a != b) 是真的。
b.) <> 如果两个操作数的值不相等,则条件为真。 (a <> b) 是真的。这类似于 != 运算符。
你可以用“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 如前所述。
标准
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]
使用
!=
或<>
。两者都代表不相等。
比较运算符
<>
和 !=
是同一运算符的不同拼写。 !=
是首选拼写; <>
已过时。 (参考:Python语言参考)