w3resource

Python Exercise: Get Fizz, Buzz and FizzBuzz

Python Conditional: Exercise-10 with Solution

Write a Python program that iterates the integers from 1 to 50. For multiples of three print "Fizz" instead of the number and for multiples of five print "Buzz". For numbers that are multiples of three and five, print "FizzBuzz".

Sample Solution:

Python Code :

# Iterate through numbers from 0 to 50 using the range function
for fizzbuzz in range(51):
    # Check if the current number is divisible by both 3 and 5 (i.e., divisible by 15)
    if fizzbuzz % 3 == 0 and fizzbuzz % 5 == 0:
        # If divisible by both 3 and 5, print "fizzbuzz" and continue to the next iteration
        print("fizzbuzz")
        continue
    # Check if the current number is divisible only by 3
    elif fizzbuzz % 3 == 0:
        # If divisible only by 3, print "fizz" and continue to the next iteration
        print("fizz")
        continue
    # Check if the current number is divisible only by 5
    elif fizzbuzz % 5 == 0:
        # If divisible only by 5, print "buzz" and continue to the next iteration
        print("buzz")
        continue
    # If the number is neither divisible by 3 nor 5, print the number itself
    print(fizzbuzz) 
	

Sample Output:

fizzbuzz
1
2
fizz
4
buzz
fizz
7
8
fizz
buzz
11
fizz
13
14
fizzbuzz
 ..... 
 
41
fizz
43
44
fizzbuzz
46
47
fizz
49
buzz

Flowchart:

Flowchart: Python program to get Fizz, Buzz and FizzBuzz

Python Code Editor :

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to get the Fibonacci series between 0 to 50.
Next: Write a Python program which takes two digits m (row) and n (column) as input and generates a two-dimensional array. The element value in the i-th row and j-th column of the array should be i*j.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.