Python中是否有“not equal”操作符?

2024-04-19 21:50:14 发布

您现在位置:Python中文网/ 问答频道 /正文

你怎么说不平等?

就像

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

有什么东西相当于==,意思是“不相等”?


Tags: noifnotequalhibyeprintelif
3条回答

当两个值不同时,有一个!=(不等于)运算符返回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运算符是用于检查两个对象是否实际上相同的对象标识运算符:

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.

使用!=。见comparison operators。为了比较对象标识,可以使用关键字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 - Basic Operators图表可能有帮助。

相关问题 更多 >