Help with the if else syntax in python

Hi guys! I just started the complete python mastery course and was going through Mosh’s solution to the exercise in section 4 - functions. He wrote his code this way:

def fizz_buzz(num):

if (num % 3 == 0) and (num % 5 == 0):
    return 'fizzbuzz'
if num % 5 == 0:
    return 'buzz'
if num % 3 == 0:
    return 'fizz'
return num

So, please I need some clearance as to why I should use if and not elif after the first if statement. thanks a lot for your help guys!

It’s just a matter of coding style. In this case, there is no logic outside of the if branch. So, you simply return and tell the reader there is nothing interesting going on afterward.

1 Like

I think it is also important to point that this works well if you return after inside the if, in other words if you break out of the function if the statement is true.

You could certainly write it like this:

if (num % 3 == 0) and (num % 5 == 0):
    return 'fizzbuzz'
elif num % 5 == 0:
    return 'buzz'
elif num % 3 == 0:
    return 'fizz'
else:
    return num

but as @some_random_coder highlights, it is a matter of style. The one without the elif does appear neater and cleaner.

2 Likes