Solving FizzBuzz in Python and JavaScript

Posted on August 14, 2023

What is FizzBuzz?

FizzBuzz is a simple coding problem used in interviews to test basic programming skills. The task is to print the numbers from 1 to a given number, but print “Fizz” instead if the number is divisible by 3, “Buzz” instead if divisible by 5, and “FizzBuzz” if divisible by both 3 and 5.

The origins of FizzBuzz are unclear, but it has become a popular interview screening technique to quickly assess a candidate’s ability to write basic code. Though simple, it requires knowledge of loops, conditionals, and modular division.

Python solution

Here is how to implement FizzBuzz in Python:

import sys

def fizzbuzz(end):
  for num in range(1, end+1):
    if num % 3 == 0 and num % 5 == 0:
      print("FizzBuzz")
    elif num % 3 == 0:
      print("Fizz")
    elif num % 5 == 0:
      print("Buzz")
    else:
      print(num)

if __name__ == "__main__":
  end = int(sys.argv[1])
  fizzbuzz(end)

Let’s break this down:

  • import sys imports the sys module to access command line arguments
  • def fizzbuzz(end): defines the fizzbuzz function
  • The main logic is inside the function:
    • Loop from 1 to end
    • Check for divisibility by 3 and 5 using %
    • Print FizzBuzz, Fizz or Buzz if conditions met
    • Else, print the number
  • if __name__ == "__main__": runs the code only if executed directly
  • end = int(sys.argv[1]) gets the end number from command line
  • fizzbuzz(end) calls the function

To run it:

python fizzbuzz.py 100

This structure allows the FizzBuzz logic to be reused by importing the script.

JavaScript solution

Here is how to implement FizzBuzz in JavaScript using Node.js:

const end = parseInt(process.argv[2]);

for (let i = 1; i <= end; i++) {
  if (i % 3 === 0 && i % 5 === 0) {
    console.log("FizzBuzz");
  } else if (i % 3 === 0) {
    console.log("Fizz");
  } else if (i % 5 === 0) {
    console.log("Buzz");
  } else {
    console.log(i);
  }
}

The logic follows the same structure:

  • Get the end number from command line argument
  • Loop from 1 to end
  • Check for divisibility by 3 and 5
  • Print FizzBuzz, Fizz or Buzz based on conditions
  • Else print the number

To run:

node fizzbuzz.js 100

FizzBuzz tests basic coding concepts in any language. By accepting input and using modular division and conditionals, we can easily solve this problem. This example demonstrates a structured approach in both Python and JavaScript.

programming javascript python interview