# Replace Multiple of 3 and 5 With Fizz, Buzz in Python

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

Suppose we have a number n. We have to find a string that is representing all numbers from 1 to n, but we have to follow some rules.

• When the number is divisible by 3, put Fizz instead of the number

• When the number is divisible by 5, put Buzz instead of the number

• When the number is divisible by 3 and 5 both, put FizzBuzz instead of the number

To solve this, we will follow these steps −

• For all number from 1 to n,
• if number is divisible by 3 and 5 both, put “FizzBuzz”
• otherwise when number is divisible by 3, put “Fizz”
• otherwise when number is divisible by 5, put “Buzz”
• otherwise write the number as string

Let us see the following implementation to get better understanding −

## Example

Live Demo

class Solution(object):
def fizzBuzz(self, n):
result = []
for i in range(1,n+1):
if i% 3== 0 and i%5==0:
result.append("FizzBuzz")
elif i %3==0:
result.append("Fizz")
elif i% 5 == 0:
result.append("Buzz")
else:
result.append(str(i))
return result
ob1 = Solution()
print(ob1.fizzBuzz(15))

## Input

15

## Output

['1', '2', 'Fizz', '4', 'Buzz', 'Fizz', '7', '8', 'Fizz', 'Buzz', '11', 'Fizz', '13', '14', 'FizzBuzz']
Updated on 23-Sep-2020 06:36:31