问题描述
假设 x
是整数,构造如果x:
在功能上与 if x!= 0:
在Python中。一些语言的样式指南明确禁止前者 - 例如,ActionScript / Flex的样式指南声明,你不应该为这种事情隐式地转换一个int到bool。
Assuming that x
is an integer, the construct if x:
is functionally the same as if x != 0:
in Python. Some languages' style guides explicitly forbid against the former -- for example, ActionScript/Flex's style guide states that you should never implicitly cast an int to bool for this sort of thing.
Python有偏好吗?
Does Python have a preference? A link to a PEP or other authoritative source would be best.
推荐答案
结构: if x:
通常用于检查布尔值。
The construct: if x:
is generally used to check against boolean values.
对于 int
显式 x!= 0
是首选的 - 沿着显式比隐式()。
For int
s the use of the explicit x != 0
is preferred - along the lines of explicit is better than implicit (PEP 20 - Zen of Python).
这篇关于在Python中首选哪个`if x:`或`if x!= 0:`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!