1

So I'm quite new to coding and I was experimenting with all the different fizzbuzzs' and I came across one using dicts.

When I run it I can easily make any parameters change with 1 keystroke change, which is nice, but I can't figure out why it prints fizzbuzz first, and then it does all of the fizzbuzzs' I choose.

Here is the code I'm using:

def fizzbuzz(multiples, *args):
    for i in range(*args):
        output = ''
        for multiple in multiples:
            if i % multiple == 0:
                output += multiples[multiple]
        if output == '':
            output = i
        print(output)
multiples={3:Fizz,5:Buzz}
fizzbuzz(multiples, 145)

stall = input("")

The output will go: FizzBuzz 1 2 Fizz ...etc.

It makes it look like 0 is a FizzBuzz...

For educational purposes: for why that?

Thank you.

DopaZilla
  • 11
  • 4
  • 3
    I think I see at least one bug on the 4th line `for multiples in multiple:` should be `for multiple in multiples:` – Key Lay May 11 '18 at 07:00
  • 1
    Even after you fix that: What do you think `0 % 3` and `0 % 5` give you? If you don't know, try it out in the interactive terminal. And meanwhile, why do you think that's wrong? 0 _is_ divisible by 3, and 5, and every other integer except 0. – abarnert May 11 '18 at 07:02
  • My bad I didn't copy and paste it I typed it by hand; it is multiple in multiples in my code. I don't know part of me did not think you could split a 0.. but... I guess you can split a 0 infinite times.. and its just never anything. That's some stuff right there. It feels weird. But it makes sense now. Thanks for that lol! – DopaZilla May 11 '18 at 07:11

1 Answers1

1

There's nothing wrong with this code, except for multiple typos (but those all raise NameError instead of causing the behavior you're asking about) and relying on the unspecified order of a dict (so you could get BuzzFizz instead of FizzBuzz, but that also isn't what you're asking about).

The reason it prints FizzBuzz is that you do this:

if i % multiple == 0:
    output += multiples[multiple]

And since 0 % 3 == 0 and 0 % 5 == 0, it's true both times, so it adds both words.

And this isn't a bug. The number 0 is divisible by 3, and 5, and every other integer except 0.

You may be confused because many FizzBuzz programs—and probably all children who play the game in school—start counting at 1 instead of 0. But range(144) starts at 0. (It also ends with 143, not 144.) You may have wanted to call fizzbuzz(multiples, 1, 145).

abarnert
  • 354,177
  • 51
  • 601
  • 671