我也碰到過這樣的一段代碼:Python:爲什麼「if <some integer>」等價於「if True」?
counts = 128 * [0]
# some other steps here that modify the variable counts...
# in the end we have something like counts=[12, 583, 0, etc. , etc., 384]
for i in range(len(counts)):
if counts[i]:
outfile.write("%-12s%d\n" % (display(i), counts[i]))
關於if
聲明,據我所知,它被引入,使其跳過指令counts[i]==0
時。這是因爲0
相當於False
。但另一方面,我認爲任何其他整數(除1之外)都不等於True
。事實上,如果我在shell上鍵入3 == True
,我會得到False
作爲答案。那麼,爲什麼if <some integer>
等於if True
?
...因爲Python中所有非零整數都是真的嗎?試試'bool(3)';你會看到當強制爲一個布爾值時,3 *變成*'True'。 –