# 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.
当两个值不同时,有一个
!=
(不等于)运算符返回True
,不过要注意类型,因为"1" != 1
。这将始终返回True,"1" == 1
将始终返回False,因为类型不同。Python是动态的,但是是强类型的,其他静态类型的语言会抱怨比较不同的类型。还有
else
子句:is
运算符是用于检查两个对象是否实际上相同的对象标识运算符:使用
!=
。见comparison operators。为了比较对象标识,可以使用关键字is
和它的否定is not
。例如
不等于
!=
(vs等于==
)你在问这样的事情吗?
这个Python - Basic Operators图表可能有帮助。
相关问题 更多 >
编程相关推荐