python

Solution of FizzBuzz problem using Python

The FizzBuzz problem is a common programming challenge. The challenge is to print the numbers from 1 to 100, but for multiples of three print "Fizz" instead of the number, and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz". The solution to the FizzBuzz problem using Python is to use the modulo operator to check for the divisibility of the number by 3 and 5.

for i in range(1,101) :
    result = ""
    if i % 3==0 : result+="Fizz"
    if i % 5==0 : result+="Buzz"
    if result == "" : print(i)
    else : print(result)

Output

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Buzz
Fizz
22
23
Fizz
Buzz
...
97
98
Fizz
Buzz

The above code iterates through the numbers 1 to 100. If the number is divisible by 3, it adds "Fizz" to the result string. If the number is divisible by 5, it adds "Buzz" to the result string. If the number is divisible by 3 and 5, it adds "FizzBuzz" to the result string. If the result string is empty, it prints the number. Otherwise, it prints the result string.

Solution 2: Without using the modulo operator(%)

This is a better approach to solving the FizzBuzz problem using Python. We are not using the modulo operator here, hence the efficiency of our program will be higher than the previous solution.

count_3 = 0
count_5 = 0
for i in range(1,101) :
    count_3 += 1
    count_5 += 1
    result=""

    if count_3 == 3:
        result+="Fizz" 
        count_3 = 0

    if count_5 == 5:
        result+="Buzz" 
        count_5 = 0

    if result == "":
        print(i)
    else:
        print(result)

Solution 3: More Pythonic way solution

As we know that Python provides different methods that can be helpful to write the program in one line. We will use the same approach here.

for i in range(1, 101) :
   print("Fizz"*(i%3<1)+(i%5<1)*"Buzz" or i)
Was this helpful?