Python's Not (Just) For Unicorns

An interactive introduction to programming in Python, for human beings and whoever else

Project

Project - FizzBuzz

So, there’s this programming thing out there called FizzBuzz. When you’re applying for a programming job, they might ask you to do it to prove that you aren’t completely incapable of programming. It’s totally stupid and dumb, but it’s totally a Thing out in the world, so we’re going to do it right this second.

Write a program that prints the numbers from 1 to 20. But 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”.

“Multiple of xxx” means “Can be divided cleanly by xxx without any extra bits left over.” For example, 9 / 3 = 3, so 9 is a multiple of 3. But 10 / 3 = 3.333, making 10 not a multiple of 3.

Instead of / and looking at the part after the decimal, we can also use modulo, %. Programmers love modulo more than anything.

print(9 % 3) print(10 % 3) if 9 % 3 == 0: print(“9 is a multiple of 3”) if 10 % 3 == 0: print(“10 is a multiple of 3”)

All right, let’s make FizzBuzz! I’ve written some code below that gives you the numbers 1 to 20 in a list, it’s your job to use that to print out the correct fizzes and buzzes and fizzbuzzes. As a hint, the first seven should look like this:

1
2
Fizz
4
Buzz
Fizz
7
numbers = list(range(1,21))
  • Hint: If numbers is a list, how do you go through every number in the list?
  • Hint: We’ll want to use a for loop to go through each number
  • Hint: We’ll need some conditionals
  • Hint: To check if a number is a multiple of some other number, use modulo
  • Hint: We’ll need to use if and elif and else, too.
  • Hint: To check for multiple conditions, we can use and. For example, if a > 10 and a < 400:
  • Hint: If we print FizzBuzz we should not be printing Fizz or Buzz
  • Hint: The order of our checking/printing is important!
  • Hint: If we’re using multiple elif, the first “true” conditional is the one that is run. Everything else gets skipped!
  • Hint: We’ll want to check first if it’s a multiple of three AND five, then three, then five.
  • Hint: Use if num % 3 == 0 and num % 5 == 0: