[Solved] What is the correct output for the FizzBuzz test in python?


Think about the order in which these statements occur,

elif (count % 5) and (count % 3):

this line of code will never execute, as either

if (count % 3) == 0:

or

elif (count % 5) == 0:

will execute first if those conditions are true. In this
case you want to check if both of these conditions are true,
only then should you check to see if a single condition is true.

Also, the line of code

count = count + 1

appears in every branch of your code, consider placing this somewhere
where it will be executed every single time.

However I would choose to use a for loop rather than a while loop,

for x in range(100):

this eliminates the need for an extra count variable.

Another thing to watch out for

elif (count % 5) and (count % 3):

here, you’re not checking if the number % 5 is == 0, you’re just checking (count % 5). So the expression “if (count % 5)” will result in True if count is not evenly divisible by 5 (check out Truth value testing). The same goes for the other places where you leave out the == comparator

Here’s an example of a similar approach to yours.

for count in range(1, 101):
    if count % 5 == 0 and count % 3 == 0:
        print "FizzBuzz"
    elif count % 5 == 0:
        print "Buzz"
    elif count % 3 == 0 and count % 5 == 0:
        print "Fizz"
    else:
        print count

things to note:

  • checking for both conditions before checking for individual conditions
  • for loop instead of while loop (personal preference)
  • checking for == 0

solved What is the correct output for the FizzBuzz test in python?