Python 将 0 评估为 False

2022-01-19 00:00:00 python boolean

问题描述

在 Python 控制台中:

In the Python console:

>>> a = 0
>>> if a:
...   print "L"
... 
>>> a = 1
>>> if a:
...   print "L"
... 
L
>>> a = 2
>>> if a:
...   print "L"
... 
L

为什么会这样?


解决方案

在Python中,boolint的子类,False值为 0;即使值没有在 if 语句(它们是)中隐式转换为 boolFalse == 0 也是 true.

In Python, bool is a subclass of int, and False has the value 0; even if values weren't implicitly cast to bool in an if statement (which they are), False == 0 is true.

相关文章