你怎么会说不等于?
比如说
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 - 基本运算符图表可能会有帮助。
有一个!=
(不相等)运算符,当两个值不同时返回真',但要注意类型,因为
"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.
既然大家都已经列出了其他大部分的不等价的说法,我就补充一下。
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中,有两个运算符用于"不等于"。 条件的两个运算符 -
a.) != 如果两个操作数的值不相等,则条件为真。 a != b)为真。
b.)<>.如果两个操作数的值不相等,则条件变为真。 如果两个操作数的值不相等,那么条件变为真。 (a <> b)为真。 这与 != 操作符类似。