The FizzBuzz problem is a well-known programming challenge often used in coding interviews. In this article, we will explore the FizzBuzz function written in Python, breaking down its components and providing a clear understanding of how it operates.
FizzBuzz Code
Let’s write the implementation of the FizzBuzz problem:
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)
# Example usage
fizzbuzz(100)
Explanation
- The function
fizzbuzz(n)
is defined to accept one parameter,n
. - The
for
loop iterates from 1 ton
(inclusive). Therange(1, n + 1)
function generates a sequence of numbers starting from 1 up ton
. - Conditional Logic:
- The first condition checks if
i
is divisible by both 3 and 5. If true, it prints “FizzBuzz”. - The second condition checks if
i
is divisible by 3. If true, it prints “Fizz”. - The third condition checks if
i
is divisible by 5. If true, it prints “Buzz”. - If none of the conditions are met, it simply prints the number
i
.
- The first condition checks if
When you call fizzbuzz(100)
, the function will print the numbers from 1 to 100, replacing multiples of 3 with “Fizz”, multiples of 5 with “Buzz”, and multiples of both with “FizzBuzz”.