Python:为什么"if <some integer>"等同于"if True"?

Gia*_*ani -1 python if-statement

我遇到过这段代码:

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]))
Run Code Online (Sandbox Code Playgroud)

关于if声明,我理解它的引入是为了在它何时跳过指令counts[i]==0.那是因为0相当于False.但另一方面,我认为任何其他整数(除了1)都不等于True.事实上,如果我3 == True在shell上输入,我会得到False答案.那么,有什么特别的理由if <some integer>相当于if True

Cha*_*ffy 5

3 == True 比较3-as-an-integer和True-as-a-boolean.

if 3: 是强制3到布尔值.

你会看到这bool(3) == True是真的.