Python中是否有“不等于”的运算符?
你会怎么说不等于?
喜欢
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)
不等于!=
(vs等于==
)
你在问这样的事情吗?
answer = 'hi' if answer == 'hi': # equal print "hi" elif answer != 'hi': # not equal print "no hi"
这个Python – 基本操作符图表可能会有所帮助。
当两个值不同时,有!=
(不等于)运算符返回True
,但要小心types导致"1" != 1
这将始终返回True和"1" == 1
将始终返回False,因为types不同,python是dynamic的,但强types,其他静态types的语言会抱怨比较不同的types。
这也是else
条款
# this will always print either "hi" or "no hi" unless something unforseen 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"
在这种情况下,它是简单的切换检查正==(真)负面和反之亦然…
您可以同时使用!=
或<>
。
不过,请注意,在不推荐使用<>
情况下,首选!=
。
使用!=
或<>
。 两者并不相等。
比较运算符<>
和!=
是相同运算符的替代拼写。 !=
是首选的拼写; <>
已经过时了。 [参考:Python语言参考]
你可以简单地做:
if hi == hi: print "hi" elif hi != bye: print "no hi"