[Solved] “FizzBuzz”-style program that checks for divisibility by multiple numbers prints numbers multiple times when it should print words


Add the “Fizz” “Buzz” “Bizz” if the division is possible, at the end if nothing has been added, it means that you have to print the number itself.

n = 0
toTest = [
    3,
    5,
    7
]
outputCanBe = [
    "Fizz",
    "Buzz",
    "Bizz"
]
outputIndex = 0
iteration = (len(toTest)) 
while n <= 25:
    n += 1
    output = ""
    for num in range(iteration):
        if n%toTest[num] == 0:
            outputIndex = num
            output += outputCanBe[outputIndex]
    if not output:
        print(n)
    else:
        print(output)

EDIT :

Here’s a cleaner and shorter version :

words = {3: "Fizz", 5: "Buzz", 7: "Bizz"}
size = 100
for n in range(size):
    output = ""
    for (numb, word) in words.items():
        if n % numb == 0:
            output += word
    print(n) if not output else print(output)

I used a dictionnary to connect a numb (example : 3) and its word (example : “Fizz”).

Doing a for loop is just for shorter code.

The .items() method is meant to unpack the (key,value) of a dictionnary.

Python consider that if a str is empty its bool value is False. If it’s not empty, no matter what it contains it’s True. That’s what the if not ouput is for, to check if output is empty (divided by none of these numbers) or not.

0

solved “FizzBuzz”-style program that checks for divisibility by multiple numbers prints numbers multiple times when it should print words