Years ago, while browsing the original wiki site, I stumbled upon the fizzbuzz test:
“Write a program that prints the numbers from 1 to 100. 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”.”
Imagine my surprise when reading that it was designed to make most programming candidates fail the test. From time to time I have the fine opportunity to introduce people who have never coded before in their lives to Python. Within the first two hours they have managed to produce a fizzbuzz version that looks like this:
for i in range(1, 101):
if i % 3 == 0 and i % 5 == 0:
print("fizzbuzz")
elif i % 3 == 0:
print("fizz")
elif i % 5 == 0:
print("buzz")
else:
print(i)
I like the myth that 99.5% of candidates fail fizzbuzz. I tell students that they now can celebrate their achievement. But this is not where I stop with the test. I can now tell them about functions and then have them make one like:
def fizzbuzz(start, stop):
:
where I have them modify their code above to make it a function. And afterwards they can learn about named parameters with default values:
def fizzbuzz(start=1, stop=100, three=3, five=5):
:
Notice above how one can change the values of 3 and 5 from the original test and try a different pair. And yes, I leave the functions as exercises to the reader :)
But the best sparks in their eyes come when they remember that I had taught them certain properties of strings some three hours ago, like:
>>> 'fizz' + 'buzz'
'fizzbuzz'
>>> 'fizz' * 1
'fizz'
>>> 'fizz' * True
'fizz'
>>> 'fizz' * 0
''
>>> 'fizz' * False
''
>>> 'fizz' + ''
'fizz'
>>>
So their first observation that 'fizz' + 'buzz'
equals 'fizzbuzz'
is followed by what is summed up by the table:
String |
Sum of strings |
Expanded sum |
‘fizzbuzz’ |
‘fizz’ + ‘buzz’ |
‘fizz’ * True + ‘buzz’ * True |
‘fizz’ |
‘fizz’ + ” |
‘fizz’ * True + ‘buzz’ * False |
‘buzz’ |
” + ‘fizz’ |
‘fizz’ * False + ‘buzz’ * True |
” |
” + ” |
‘fizz’ * False + ‘buzz’ * False |
Which makes them write something like that in the end:
def fizzbuzz(x, y):
return 'fizz' * x + 'buzz' * y
for i in range(1, 101):
print(fizzbuzz(i % 3 == 0, i % 5 == 0) or i)
How many things one can learn within a day starting from zero using the humble (and sometimes humbling) fizzbuzz.