design, write and debug programs that accomplish specific goals, including controlling or simulating physical systems; solve problems by decomposing them into smaller parts.

use logical reasoning to explain how some simple algorithms work and to detect and correct errors in algorithms and programs

6.6b

LO: FizzBuzz/To debug simple programs.

Let's have a look at some possible situations that may have arisen during the fizzbuzz challenge:


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

			

This code does does not make a choice, it just does everything. For example it will print out 1, 2, fizz, 3 - we want it to print out fizz instead of 3. When it gets to 15 the code just prints out everything!


Back in 5.3a when the if statement was introduced it was explained that when multiple if statements are used, if they are True then they will happen. If we wanted to only make one choice (as we do here) then we would want to use the elif statement (else if).



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


			

Now only one choice is made but where is 'fizzbuzz'?

This problem is caused by the order of the statements. If we work through the statments from the top down (as Python would do) if we were the number 15 then when we get to the first statement if i % 3 == 0: we find that the statement is True - 15 is divisable by 3 so only that statement is carried out. If we change the order of the statements we find that this problem is solved:


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


			

There are debug versions of the programs covered in the code example section below.


Code Examples

Resources