Skip to content

fizzbuzz python

The FizzBuzz problem is a classic programming challenge that is often asked in technical interviews. It is a simple problem to understand, but it can be tricky to solve efficiently, especially for beginners.

The goal of the FizzBuzz problem is to write a program that prints the numbers from 1 to n, but for multiples of 3, print “Fizz” instead of the number, and for multiples of 5, print “Buzz”. For numbers that are multiples of both 3 and 5, print “FizzBuzz”.

Here is a simple solution to the FizzBuzz problem in Python:

Python

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


if __name__ == "__main__":
  fizzbuzz(100)

Output:

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
...
97
Fizz
99
Buzz

This solution works by iterating over the numbers from 1 to n. For each number, it checks if it is divisible by 3 and 5. If it is, then it prints “FizzBuzz”. If it is only divisible by 3, then it prints “Fizz”. If it is only divisible by 5, then it prints “Buzz”. Otherwise, it prints the number itself.

This is just a simple solution to the FizzBuzz problem. There are many other ways to solve it, and some solutions may be more efficient than others. However, this solution is a good starting point for beginners.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)