Mastodon

One of the aphorisms of the Zen of Python says:

Explicit is better than implicit.

Go dehl writes this code to solve FizzBuzz:

for i in range(1, 101):
    print('FB' if not i % 15 else 'F' if not i % 3 else 'B' if not i % 5 else i)

Read that expression out loud: “the string 'FB' If not i modulus 15; else 'F' if no i modulus 3; else 'B' if not i modulus 5; else i”. It sounds exactly like the opposite of the solution! Why? Because Go dehl is (ab)using the fact that 0 is false-y. A number a is a multiple of another number b if a % b is 0, and 0 evaluates to False in boolean context[1], so he's negating that instead of writing if i % 15 == 0 . It's a tendency that I also see in other languages where they write a && b instead of if a: b. Sometimes we get used to these shorthands, but in this case, to me, it was completely confusing. So, please, “Explicit is better than implicit”.

I would have written this as a comment on their blog, but it only works if I login with a Google account, which I don't have; hence, this post.


python


[1] See my previous take on this