How do I write FizzBuzz well?
Short answer
Check the combined condition first, or build the string by appending. Both avoid the repeated i % 15 check and both extend cleanly.
for i in range(1, 101):
if i % 15 == 0:
print("FizzBuzz")
elif i % 3 == 0:
print("Fizz")
elif i % 5 == 0:
print("Buzz")
else:
print(i)Correct, and fine as a first answer. Order matters: put the 15 case first or it is never reached.
#The version that extends
for i in range(1, 101):
output = ""
if i % 3 == 0: output += "Fizz"
if i % 5 == 0: output += "Buzz"
print(output or i)No % 15 at all — it falls out of both conditions being true. Adding a seventh rule means one more if, not four more branches.
output or i uses the fact that an empty string is falsy.
#Fully data-driven
RULES = [(3, "Fizz"), (5, "Buzz"), (7, "Bang")]
for i in range(1, 101):
output = "".join(word for n, word in RULES if i % n == 0)
print(output or i)Now the rules are data. Whether this is better depends entirely on whether the rules actually change — offering it and saying that is the right move.
#What the interviewer is watching for
- Do you handle the 15 case, or print "Fizz" for 15?
- Do you start at 1 or 0?
- Do you talk before typing?
- If asked to add a rule, does your solution absorb it or need restructuring?
#Do not over-engineer it
Presenting a class hierarchy with a strategy pattern for FizzBuzz reads as poor judgement, not sophistication. Write the clear version, mention how you would extend it, and move on.