I’ve been dabbling in Python recently, and stumbled across the FizzBuzz exercise, so I decided to test myself doing it in Python as a learning experience.

Now, since I am the proctor and test subject, I let myself have two concessions:

1. I was going to use a text editor, because this was for my own learning, not for an interview, and I didn’t feel like writing code longhand on paper. It’s my understanding that this condition is mainly there to prevent anyone from using the Internet to search for a solution.

2. I knew I could write this in C/C++ blindfolded with my hands tied behind my back, and that Python was my own choice to make it more educational. So, if I came across an obstacle where my unfamiliarity with Python was a limiting factor, I was going to let myself search for specific resolutions to that. This turned out to be necessary (and educational, as I hoped!).

So, I fired up IDLE and threw together a quick script:

import sys
for i in range(1,100):
if(i % 3) == 0:
if(i % 5) == 0:
print i,

Apologies, Drupal seems to be eating my indents despite the <code> tag.

It didn’t start out exactly like that. First, I used the basic python print command, but that automatically adds a newline (which I knew). Then, I tried adding a comma after the Fixx, Buzz and i prints, which suppresses the newline — but appends a SPACE instead. 🙁 This resulted in almost-perfect output, however, it printed “Fizz Buzz” instead of “FizzBuzz” and the exercise says “FizzBuzz” so I thought I needed to do better.

Not having much skill with Python print formatting, I decided to allow myself a phone-a-Google and looked up details of Python formatting. Apparently the new print() function in Python 3 lets you control EOL formatting, but I didn’t have Python 3 available. So, the next best suggestion was to use the sys.stdout.write() function. I changed the Fizz and Buzz statements to that, leaving the print i as a print-with-comma, because as I understand, sys.stdout.write doesn’t do any formatting. And, the trailing space appended after printing i would not be an issue, since nothing needs to append to it on the same line. There’s a blank print at the end of the loop to force a newline no matter what printed previously.

One can debate about whether this is the best or most elegant or most efficient. I think it is both elegant and efficient. There aren’t multiple tests of the modularity of the number i, there aren’t tangled else/if and and tests. Some might quibble about the use of the extra print_number variable as being efficient, but I think it lends clarity to the code that other “more efficient” solutions lack.

This is the posting that sent me on this fowl-chase. And it cites this as some interesting solutions to the problem, and the FizzBuzzBazz variant. I think my design adapts well to FizzBuzzBazz.