# 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"
使用
!=
。见比较运算符。对于比较对象的同一性,你可以使用关键字is
和它的否定词is not
。例如
不等于
!=
(对等于=
)。你问的是类似这样的问题吗?
这个Python - 基本运算符图表可能会有帮助。
有一个
!=
(不相等)运算符,当两个值不同时返回真',但要注意类型,因为
"1" !=1。这将总是返回True,而
"1" == 1`将总是返回False,因为类型不同。Python是动态的,但却是强类型的,其他静态类型的语言会抱怨不同类型的比较。还有 "else "子句。
is "运算符是对象身份运算符,用于检查两个对象是否真的相同。
你可以同时使用
!=
或<>
。但是,请注意,在
<>
被废弃的情况下,!=
是首选。既然大家都已经列出了其他大部分的不等价的说法,我就补充一下。
在这种情况下,它是简单的切换检查正= =(真)到负,反之亦然... ...
在Python中,有两个运算符用于"不等于"。 条件的两个运算符 -
a.) != 如果两个操作数的值不相等,则条件为真。 a != b)为真。
b.)<>.如果两个操作数的值不相等,则条件变为真。 如果两个操作数的值不相等,那么条件变为真。 (a <> b)为真。 这与 != 操作符类似。
使用
!=
或<>
。 两者都代表不相等。比较运算符
<>
和!=
是同一运算符的交替拼写。!=
是首选拼写。<>
是过时的。 [参考文献。 Python语言参考]你可以简单的做。