1

I am writing a function fizzbuzz and what I want to do is input value and return it as fizz, buzz or fizzbuzz. However, there is a problem with my code. Whenever I run this, I just only get the first condition and it does not continue. Here is the code below for you:

a=int(input('Enter a number: '))

def fizzbuzz(a):

    if a % 3 == 0:

        return ('Fizz')

    elif a % 5 == 0:

        return ( 'Buzz' )

    elif a % 15 == 0:

        return ('Fizzbuzz')

    else:

        return a

print(fizzbuzz(a))
Terry Jan Reedy
  • 18,414
  • 3
  • 40
  • 52
Leo Zarni
  • 13
  • 1
  • 3

3 Answers3

0

The problem is in the ordering of your if conditionals.

Consider that if a is divisible by 15 then it is also divisible by 3 and 5 and so your code will just enter the first conditional and not the one you want.

Arrange the conditionals in descending order of 15, 5, 3 etc. and you should see what you want.

  • The reason I wrote 15 is that I did not want to use the and operator. What I want to do is print fizzbuzz if that number is both divisible by 3 and 5 and since 15 is also divisible by them, I used 15 as a conditional. Am I wrong? – Leo Zarni Feb 25 '20 at 15:49
0
def fizzBuzz(n):
    for n in range(1,n+1):
        if n % 3 == 0 and n % 5 == 0:
            print('FizzBuzz')
        elif n % 3 == 0:
            print('Fizz')
        elif n % 5 == 0:
            print('Buzz')
        else:
            print(n)

if __name__ == '__main__':
    n = int(input().strip())
    fizzBuzz(n)
minTwin
  • 1,181
  • 2
  • 21
  • 35
-1

Be sure that your conditions are checked in the right order.

A Fizzbuzz number is also a Fizz (divisible by 3) and a Buzz (divisible by 5), just to be clear. In the code you wrote if you ask the function if 15 is a Buzz, since it is the 1st check, you will get a positive result.

The condition you want to test here is not if a number is divisible by 15 but if a number is divisible by 3 and 5 at the same time.

Given this explanation you need to write conditions a bit differently:

a=int(input('Enter a number: '))

def fizzbuzz(a):
    if a % 3 == 0 and a % 5 == 0:
        return('Fizzbuzz')
    elif a % 3 == 0:
        return('Fizz')
    elif a % 5 == 0:
        return('Buzz')
    else:
        return a

print(fizzbuzz(a))
Pitto
  • 8,229
  • 3
  • 42
  • 51
  • Hey so I changed from 15 to 3 and 5 and the code works. I dont need the range from 0 to 50 too but still, thanks for your help! – Leo Zarni Feb 25 '20 at 15:55