你怎么说不相等呢?
就像
if hi == hi:
print "hi"
elif hi (does not equal) bye:
print "no hi"
是否有等价于==的东西表示“不相等”?
你怎么说不相等呢?
就像
if hi == hi:
print "hi"
elif hi (does not equal) bye:
print "no hi"
是否有等价于==的东西表示“不相等”?
当前回答
您可以同时使用!=或<>。
但是,请注意!=在<>被弃用的地方是首选的。
其他回答
鉴于其他人已经列出了大多数表示不平等的其他方式,我只想补充一句:
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"
在这种情况下,它是简单的切换检查positive == (true)到negative,反之亦然…
在Python中有两个运算符用于“不等于”条件-
a.) !=如果两个操作数的值不相等,则条件为真。 (a != b)是正确的。
b.) <>如果两个操作数的值不相等,则条件为真。 (a <> b)为真。这类似于!=操作符。
您可以使用!=运算符来检查是否不相等。
此外,在Python 2中有<>操作符,它曾经做同样的事情,但在Python 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.
您可以同时使用!=或<>。
但是,请注意!=在<>被弃用的地方是首选的。