My FizzBuzz solution in Python

Berry de Witte
2 min readJul 4, 2019

--

Recently i was taking a course into Databricks and with that came a basic training in Python (as this is one of the supported languages). Although i already experimented a little bit with it in my past, my skills were a little bit rusty so the teacher gave us a simple task, create the Fizz-Buzz function which is also used by many software companies in a job interview to determine if a candidate can actually write some code.

So what is a ‘Fizz-Buzz’?
Mainly it’s a very simple programming task which has a function that can return different values depending on the numeric input. In our case it should return fizz if the input is divisible by 5, buzz if it’s divisible by 7 and fizz-buzz if it’s divisible by both.

Although it’s a simple function, there are some catches. First you’ll have to know about the modulo % operator. You could write your own function for this, but i think it should be a known operator to a developer.

The modulo operation finds the remainder after division of one number by another

In this case you want to check if the remainder of your input is 0 as that means that your input is divisible like input%5 == 0.

Second catch is the third case of this task to check if the input is divisible by either 5 and 7. If you want to use a classic if/elif structure for this, you’ll want to make sure you test this as your first case.

def fizzBuzz(input):
if input%5 == 0 and input%7 == 0:
return 'fizz-buzz'
elif input%5 == 0:
return 'fizz'
elif input%7 == 0:
return 'buzz'

My shorthand solution
When working on the solution, i started breaking it down with the if/elif statement (as above) but i found myself repeating some same code and on that point i thought i could gold plate the solution a little but. So i put the result of the divisions as a string in variables and just returned the concatenated result of that. For computing the correct string i used the shorthand if notation.

def fizzBuzz(input):
fizz = 'fizz' if input%5 == 0 else ''
buzz = 'buzz' if input%7 == 0 else ''
dash = '-' if fizz and buzz else ''
return fizz + dash + buzz

So when calling the function it should return the following results:

fizzBuzz(15) returns fizz
fizzBuzz(49) return buzz
fizzBuzz(35) returns fizz-buzz
fizzBuzz(22) returns an empty string

--

--