5 ms·
Furthermore I would prefer def even(x): return not(x % 2)
by eriknstr 9y ago
Furthermore I would prefer
def even(x): return not(x % 2)
- scott_s 9y agoI would not. That's incidentally depending on non-zero numbers to become True, and zero to become False. I would prefer to think of the operation as "is x modded by 2 equal to zero?" rather than "does x modded by 2 become true when negated?"
- Veedrac 9y agoThough you might find core developers disagreeing with that sentiment. https://stackoverflow.com/a/3175293/1763356 https://stackoverflow.com/a/3175293/1763356
- scott_s 9y agoI do find it interesting, but it doesn't change what's easier for me to reason about. I suspect that it will be easier for core Python developers rather that general Python programmers because they will be more intimately familiar with the conversion rules. I would be more comfortable with such a construct in C or C++, because I am more confident in those conversion rules. But, even though Python's are quite similar, I had to check myself before making my comment, because I knew they were similar, but I was not sure what they were. The situation in the stackoverflow comment is also not quite the same: asking a question about the relationship of numbers (is x modded by 2 equal to zero) is a special case of using integers in a boolean context. Saying it's Pythonic to use an integer in a boolean context does not necessarily mean it's best to always do so.
- eriknstr 9y ago> incidentally depending on non-zero numbers to become True, and zero to become False I don't feel that there is anything incidental about that. Integer zero is logically false and any other integer is logically true.
- scott_s 9y agoIncidental to properties of numbers themselves; it's a part of the language, not a part of numbers. The function is asking a question about the property of numbers. I find it more clear when the computation to determine that property depends on number properties, not language properties.
- eriknstr 9y agoThat is a good point, and it makes sense to think of it that way. However I think that it can also be a bit "dangerous" to think too much in terms of the properties of the numbers when working with software due to the fact that for example arbitrary floats cannot be precisely represented in a limited amount of bits like we have in computers. I already hold the view that the numbers we are dealing with when working on computers are an incomplete representation of the ideals of ℝ and ℂ and their likes, so to me then it is ok to reason about code in terms of properties that stem from the language in use.
- Veedrac 9y agonot isn't a function; no need for brackets.
- eriknstr 9y agoI use parentheses liberally so I don't have to think about precedence so much both when writing and when later reading. That said I don't add unneeded parentheses for simple expressions or sub-expressions consisting only of exponents, multiplications, divisions, additions and/or subtractions.