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.
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.
== 0 means "equal to 0 (zero)".
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.
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.
The construct: if x:
is generally used to check against boolean values.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With