In this video, we're going to look at how to solve FizzBuzz problems in Python
Video Transcription
Hi my name is Art and I teach Python at Noble Desktop. In this video, I'm going to show you how to solve a very popular problem called FizzBuzz.
Before we begin, I recommend you watch my other videos on how to use functions and range, and even the modulo operator.
The problem goes like this: we need to get numbers in a range from 1 to 100 (inclusive) and then check each number. If the number is divisible by 3 with no remainder, then we want to print "Fizz". If the number is divisible by 5 with no remainder, then we want to print "Buzz". However, if the number is divisible by 3 and 5 (e.g. 15), we need to print "FizzBuzz".
Let's get started! First, let's generate a range of numbers. To do that, we'll use the function range() (which requires start, stop, and step arguments). We'll start at 1, stop at 101 (since stop is exclusive), and step by 1. Let's print "number" so we can see what numbers we get.
Now, we need to divide each number by 3 and 5. Every time the number is divisible with no remainder, we get 0. So, I could write this condition: if the number is divisible by 3 with no remainder, I want to print "number Fizz".
Next, I need to use an if statement because every time the number is divisible by 5 with no remainder, I want to print "number Buzz".
Finally, just to see what numbers are left, I'll use an else statement and print "number".
Now, let's check the results. We get "Fizz" for numbers divisible by 3 with no remainder, "Buzz" for numbers divisible by 5 with no remainder, and "FizzBuzz" for numbers divisible by both 3 and 5.
We should note that the order of operation is very important. The if statement checking for numbers divisible by 3 and 5 should be placed first. Otherwise, the code will never check if the number is divisible by 5.
That was a classical job interview problem, FizzBuzz. Watch my next video where I will show you how to solve another popular problem – how to build a multiplication table using the function range.