LearnFrenzy
Sign in Take a free test

Conditional Statements · Conditional Statements Coding Problems · Question 8

FizzBuzz from 1 to 15 in Python Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 8 Back to Exercise

Print the numbers 1 to 15, but print Fizz for multiples of 3, Buzz for multiples of 5 and FizzBuzz for multiples of both.

Solution
main.py Run
for n in range(1, 16):
    if n % 15 == 0:          # test the combined case FIRST
        print("FizzBuzz")
    elif n % 3 == 0:
        print("Fizz")
    elif n % 5 == 0:
        print("Buzz")
    else:
        print(n)

Output Verified by running it on Python 3

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz

If n % 3 were tested first, 15 would print Fizz. The most specific condition goes first.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links