Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which of `if x:` or `if x != 0:` is preferred in Python?

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.

Does Python have a preference? A link to a PEP or other authoritative source would be best.

like image 748
Cory Petosky Avatar asked Jul 09 '10 21:07

Cory Petosky


People also ask

What does =! Mean in Python?

In Python != is defined as not equal to operator. It returns true if operands on either side are not eual to each other, and returns false if they are equal.

What does == 0 mean in Python?

== 0 means "equal to 0 (zero)".

What does if not X mean in Python?

If not statements The expression, not x can mean True or False. Numeric zero (0), empty value or a None object assigned to a variable are all considered False, or True in Python. As x here is True, not x makes it False. Hence, the Else part of the code is executed.

Does 0 evaluate to true in Python?

Python assigns boolean values to values of other types. For numerical types like integers and floating-points, zero values are false and non-zero values are true.


1 Answers

The construct: if x: is generally used to check against boolean values.

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).

like image 174
Yuval Adam Avatar answered Sep 27 '22 19:09

Yuval Adam