FizzBuzz in Python
for n in range(1, 101):
if n % 15 == 0:
print("FizzBuzz")
elif n % 3 == 0:
print("Fizz")
elif n % 5 == 0:
print("Buzz")
else:
print(n)
FizzBuzz in JavaScript
for (let n = 1; n <= 100; n++) {
if (n % 15 === 0) console.log("FizzBuzz");
else if (n % 3 === 0) console.log("Fizz");
else if (n % 5 === 0) console.log("Buzz");
else console.log(n);
}
Why check 15 first?
A number divisible by both 3 and 5 is divisible by 15. If you checked 3 first, the number 15 would print “Fizz” and stop before it ever reached the “both” case. Testing 15 at the top fixes that.
A cleaner version without 15
for n in range(1, 101):
out = ""
if n % 3 == 0:
out += "Fizz"
if n % 5 == 0:
out += "Buzz"
print(out or n)
Here the string builds up “Fizz”, “Buzz”, or “FizzBuzz”, and out or n prints the number when the string is empty.
Frequently asked questions
Why is FizzBuzz such a common interview question?
It is a quick way to check that a candidate can translate simple rules into working code, use a loop, and handle the order of conditions correctly.
What does the % operator do?
It returns the remainder of a division. n % 3 == 0 is true when n divides evenly by 3.
Practice loops and conditionals in our free Python and JavaScript courses.