我刚刚开始学习 Python。我遇到了以下代码
if 0:print "And now for something completely different..."
else:print "What's all this, then?"
我知道输出应该是 What's all this, then? 但我似乎找不到合适的解释。希望有人能让我明白这一点。
谢谢。
请您参考如下方法:
0 在 bool 上下文中是 False。同样适用于空字符串、列表等。
来自python docs :
In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: False, None, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true. (See the __nonzero__() special method for a way to change this.)
