or better yet i % 2 == 0
Yeah, I don't think you can use i % 2 as an equivalent of i % 2 == 0. Maybe it's a python 3 thing, but on my 2.6.1 the mod operator just returns the remainder, it doesn't change its output if it's a boolean context (which would be perlish and highly unpythonic).
I think i % 2 is just straight up incorrect.
If we're talking about style, I think i % 2 == 0 is much more clear than (not i % 2). It says explicitly that the remainder of i divided by 2 is 0.
> Yeah, I don't think you can use i % 2 as an equivalent of i % 2 == 0. Maybe it's a python 3 thing, but on my 2.6.1 the mod operator just returns the remainder, it doesn't change its output if it's a boolean context (which would be perlish and highly unpythonic).
$ python3
>>> not 0
True
Python doesn't have Perl-like contexts, but it does treat lots of values as True or False. I do agree that i % 2 == 0
is more explicit here.I would go for more pythonic "not i % 2".
I would argue that that is not very pythonic, since it breaks the "explicit is better than implicit" guideline.
Re:The Zen of Python by Example
by koenigdavidmj on Thursday February 10, 2011 @08:03PM
(#2204684)
Most Python people are okay with relying on the behaviour of what is truthful and what is not. They would often prefer to see
if foo:
do_stuff()
over if len(foo) > 0:
do_stuff()I agree. Using the truthiness of non-boolean values has always seemed questionable in any language (Javascript is possibly the worst offender). For many statically typed languages this is caught as a syntax error, which is nice for those of use prone to occasionally typos.
The boolean equivalents of non-boolean values are well-defined and fairly simple in Python, and I believe it's encouraged (or at least extremely common) to use them as such.
In Haskell this is caught as a type error. But you can make your own version:
class ExtendedBool t where
toBool :: t -> Bool
instance ExtendedBool Int where
toBool = (0/=)
instance ExtendedBool [a] where
toBool = not . null
if' v a b =
if (toBool v)
then a
else b
main = if' "String"
(print "True")
(print "False")
This isn't meant to detract from the truth that "Beautiful [code] is better than ugly," I merely thought the implementation should be correct.