Mosh states his code is the cleanest possible solution to this problem, and I get why it is cleaner, but he fails to account for 0 as the input and therefore failed his own exercise… am I wrong?
This is his code…
def fizz_buzz(input):
if (input % 3 == 0) and (input % 5 == 0):
return “FizzBuzz”
if input % 3 == 0:
return “Fizz”
if input % 5 == 0:
return “Buzz”
return input
I would not take the lesson too literally. If you understood the concept he was trying to explain then you are in ok shape.
Your fizzbuzz, fizz, and buzz variables are all returning Booleans. Your if statement’s conditions are checking for a Boolean, no? You don’t need to compare true to true or false to false.
if fizzbuzz: # <= fizzbuzz variable is already true or false
# run code
if the true branch of an if ends with a return statement a statement on the same level of indention as if the if can only be reached in the false case. So you don’t need to explicitly use else or elif if you want to execute code only in the false case.
This is my bad code before I’ll see Mr.Mosh’s answer.
def fizz_buzz(a, b=1) :
if a % 3 == 0:
a = “fizz”
return a
elif a * b == 15:
a = “fizz_my_buzz”
return a
elif a % 5 == 0:
a = “buzz”
return a
else:
return"fizz_buzz"
The solution to your question is actually very easy, it looks like Mr Hamedani forgot to mention the 0 and negative integer numbers(like -3 and -5) input, here’s my answer added to Mr Mosh’s solution(line 2 and 3):
def fizz_buzz(input): if input <= 0: return input
if (input % 3 == 0) and (input % 5 == 0):
return “fizz_buzz”
if input % 3 == 0:
return “fizz”
if input % 5 == 0:
return “buzz”
return input