Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is fizzbuzz not working when the condition with two numbers comes after the conditions with one number?

I am trying to do the well known fizzbuzz problem in python, but do not understand, why Python is not checking the "combined" criteria.

Here is my code:

i = 0

while i + 1 < 100:
    i = i + 1
      
    if i % 3 == 0:
        print(str(i) + " fizz")
    elif i % 5 == 0:
        print(str(i) + " buzz")
    elif (i % 3 == 0 and i % 5 == 0):
        print(str(i) + " fizzbuzz")
    
    else:
        print(str(i))

I do not understand why it is not writing fizzbuzz in the cases where it can divide by 3 and 5.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I wanted to see either "fizz" or "buzz" or "fizzbuzz" but I only see "fizz" or "buzz". Why?

>Solution :

I do not know why this works, but this works for me.

I just put the conditions checking both "things" on top.

Here:

i = 0

while i + 1 < 100:
    i = i + 1
    if (i % 3 == 0 and i % 5 == 0):
        print(str(i) + " fizzbuzz")
    
    elif i % 3 == 0:
        print(str(i) + " fizz")
    elif i % 5 == 0:
        print(str(i) + " buzz")
    
    else:
        print(str(i))

I hope this works for you, sadly, I cannot explain why this is they way it is.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading