我一直认为在条件中使用-1总是与写作False(布尔值)相同。但是从我的代码,我得到不同的结果:在Python中,-1和False有区别吗?
用真和假:
def count(sub, s):
count = 0
index = 0
while True:
if string.find(s, sub, index) != False:
count += 1
index = string.find(s, sub, index) + 1
else:
return count
print count('nana', 'banana')
结果:需要长期的译员回应。
使用1和-1:
def count(sub, s):
count = 0
index = 0
while 1:
if string.find(s, sub, index) != -1:
count += 1
index = string.find(s, sub, index) + 1
else:
return count
print count('nana', 'banana')
结果:1
为什么使用-1和1给我正确的结果,而使用布尔值true和false不要?
[为什么1 == True但是2!= True在Python?](http://stackoverflow.com/questions/7134984/why-does-1-true-but-2-true-in -python) – agf
我们刚刚在Python中提出了一个关于'True'和'False'的问题。 '-1'在Python中不是'False','0'是False。在发布问题之前,请搜索这样的内容。 – agf
另请参阅[python-true-false](http://stackoverflow.com/questions/5119709/python-true-false),[why-cant-python-handle-true-false-values-as-i-expect ](http://stackoverflow.com/questions/2055029/why-cant-python-handle-true-false-values-as-i-expect),[is-false-0-and-true-1-in-蟒-AN-实现细节或 - 是 - 它担保](http://stackoverflow.com/questions/2764017/is-false-0-and-true-1-in-python-an-implementation-detail -or-it-it-guarantee),[true-false-true] – agf