在Python中首选哪个`if x:`或`if x!= 0:`? [英] Which of `if x:` or `if x != 0:` is preferred in Python?

查看:1312
本文介绍了在Python中首选哪个`if x:`或`if x!= 0:`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设 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 是首选的 - 沿着显式比隐式 PEP 20 - Python禅宗)。

For ints 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:`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆