Note: Click on "Kernel" > "Restart Kernel and Run All" in JupyterLab after finishing the exercises to ensure that your solution runs top to bottom without any errors. If you cannot run this file on your machine, you may want to open it in the cloud .
The exercises below assume that you have read Chapter 3 .
The ...
's in the code cells indicate where you need to fill in code snippets. The number of ...
's within a code cell give you a rough idea of how many lines of code are needed to solve the task. You should not need to create any additional code cells for your final solution. However, you may want to use temporary code cells to try out some ideas.
The kids game Fizz Buzz is said to be often used in job interviews for entry-level positions. However, opinions vary as to how good of a test it is (cf., source
).
In its simplest form, a group of people starts counting upwards in an alternating fashion. Whenever a number is divisible by 3, the person must say "Fizz" instead of the number. The same holds for numbers divisible by 5 when the person must say "Buzz." If a number is divisible by both numbers, one must say "FizzBuzz." Probably, this game would also make a good drinking game with the "right" beverages.
Q1: First, create a list numbers
with the numbers from 1 through 100. You could type all numbers manually, but there is, of course, a smarter way. The built-in range() may be useful here. Read how it works in the documentation. To make the output of range()
a
list
object, you have to wrap it with the list() built-in (i.e.,
list(range(...))
).
numbers = ...
Q2: Loop over the numbers
list and replace numbers for which one of the two (or both) conditions apply with text strings "Fizz"
, "Buzz"
, or "FizzBuzz"
using the indexing operator []
and the assignment statement =
.
In Chapter 1 , we saw that Python starts indexing with
0
as the first element. Keep that in mind.
So in each iteration of the for
-loop, you have to determine an index
variable as well as check the actual number
for its divisors.
Hint: the order of the conditions is important!
for number in numbers:
...
...
...
...
...
...
...
Q3: Create a loop that prints out either the number or any of the Fizz Buzz substitutes in numbers
! Do it in such a way that the output is concise!
for number in numbers:
print(...)