0

Print the numbers in the range with following constraints. if number is multiple of 3 print fuzz if number is multiple of 5 print buzz if number is multiple of 3 and 5 print fizzbuzz

sample input:        sample output
2                    1
                     2
3 15                 Fizz
                     1
                     2
                     Fizz
                     4
                     Buzz
                     Fizz
                     7....
                     fizzbuzz

I'm new to this programming.I've tried like this. I'm making some mistake please someone suggest some solution.Thanks in advance

for i in range (1,15):
 if(i%3 ==0):
  print("fizz")
 elif(i%5==0):
  print("buzz")
 elif(i%3 ==0 and i%5==0):
  print("fizzbuzz")
 else:
  print(i)

Actual output which i got
1
2
fizz
4
buzz
fizz
7
8
fizz
buzz
11
fizz
13
14
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62

4 Answers4

1

Start with the AND. The conditional will run then exit from the block upon the first matching condition

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)

What it is doing with yours is matching the if(i%3 ==0) and not making it to the if(i%3 ==0 and i%5==0) because it did match the first rule

ggdx
  • 3,024
  • 4
  • 32
  • 48
0

You will never get to your third if, because anything that matches i%3 ==0 and i%5==0 has already matched. So changing the order will fix it.

SV-97
  • 431
  • 3
  • 15
0

You check for the simples first, which means that once you check 15, it verifies that it is divisable by 3 and therefore simply prints "Fizz" and moves on, without reaching the check for AND i%5==0.

Berantzino
  • 41
  • 2
0

Like others mentioned the problem is that you first have to check the condition: if (i % 3 == 0 and i % 5 == 0). Then you should also note that the range function does not include the second limit, so you need to use range(1, 16) in your test.

So the code should be:

for i in range(1, 16):
    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)

This prints out:

1
2
fizz
4
buzz
fizz
7
8
fizz
buzz
11
fizz
13
14
fizzbuzz
gil.fernandes
  • 12,978
  • 5
  • 63
  • 76