我一直認爲在條件中使用-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