Python Exercise: Get Fizz, Buzz and FizzBuzz
Python Conditional: Exercise-10 with Solution
Write a Python program which iterates the integers from 1 to 50. For multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz".
Python Code :
for fizzbuzz in range(51): if fizzbuzz % 3 == 0 and fizzbuzz % 5 == 0: print("fizzbuzz") continue elif fizzbuzz % 3 == 0: print("fizz") continue elif fizzbuzz % 5 == 0: print("buzz") continue print(fizzbuzz)
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
Visualize Python code execution:
The following tool visualize what the computer is doing step-by-step as it executes the said program:
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.
Python: Tips of the Day
timeit library is great for timing Python execution times. Just pass a function in string format to timeit.timeit() method and it will carry out 1 million executions to report the minimum time the code takes.
Its very useful to compare small code pieces and different functions but can be sluggish with big code.
Check out the example below demonstrating the execution time difference between 2 very similar list comprehension methods in Python:
import timeit lst1='''list(range(100))''' lst2='''[i for i in range(100)]''' a=timeit.timeit(lst1) b=timeit.timeit(lst2) print(a, b, sep="------")
- New Content published on w3resource:
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework