Aj *_*ity 366 python operators
你怎么说不相等?
喜欢
if hi == hi:
print "hi"
elif hi (does not equal) bye:
print "no hi"
Run Code Online (Sandbox Code Playgroud)
有没有相当于=="不平等"的东西?
tsk*_*zzy 593
使用!=.查看比较运算符.要比较对象标识,可以使用关键字is及其否定is not.
例如
1 == 1 # -> True
1 != 1 # -> False
[] is [] #-> False (distinct objects)
a = b = []; a is b # -> True (same object)
Run Code Online (Sandbox Code Playgroud)
Lev*_*von 56
不相等 != (vs相等==)
你在问这样的事吗?
answer = 'hi'
if answer == 'hi': # equal
print "hi"
elif answer != 'hi': # not equal
print "no hi"
Run Code Online (Sandbox Code Playgroud)
这个Python - Basic Operators图表可能会有所帮助.
Sam*_*lar 24
还有的!=(不等于)运算符返回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"
Run Code Online (Sandbox Code Playgroud)
该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.
Run Code Online (Sandbox Code Playgroud)
看到其他人已经列出了大多数其他说不相等的方法我将只添加:
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"
Run Code Online (Sandbox Code Playgroud)
在这种情况下,简单地将正==(真)的检查切换为否定,反之亦然......