The most famous warm-up question: it checks that you can write a loop and a condition cleanly, and test them.
What to build
A program that prints the numbers from 1 to n, replacing some of them with words.
Requirements
- Print
Fizzfor multiples of 3,Buzzfor multiples of 5 andFizzBuzzfor multiples of both. - Print the number itself otherwise. One value per line.
Input
One integer n.
Output
n lines.
Constraints
1 ≤ n ≤ 1000.
Example
Input:
5
Output:
1
2
Fizz
4
Buzz
Why it works
Each number needs exactly one output. Checking the combined case first means a multiple of 15 does not stop at the Fizz or Buzz rule.
Examples
Example 1 · Input
5
Expected output
1 2 Fizz 4 Buzz
Example 2 · Input
15
Expected output
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Test for 15 (or for both 3 and 5) before testing for 3 alone or 5 alone.
Hint 2
`i % 3 == 0` tells whether i is a multiple of 3.
Hint 3
Print the number itself when none of the rules apply.
Solution
Show one correct solution (try it yourself first)
n = int(input())
for i in range(1, n + 1):
if i % 15 == 0:
print("FizzBuzz")
elif i % 3 == 0:
print("Fizz")
elif i % 5 == 0:
print("Buzz")
else:
print(i)
▶ Open this solution in the compiler, then press Visualize to watch it run step by step