-4

I have been given this question to do in Python:

Take in a list of numbers from the user and run FizzBuzz on that list.

When you loop through the list remember the rules:

  1. If the number is divisible by both 3 and 5 print FizzBuzz

  2. If it's only divisible by 3 print Fizz

  3. If it's only divisible by 5 print Buzz

  4. Otherwise just print the number

Also remember elif!

I have the following script created, but it gives me an error at if n%3=True

n = input()
if n % 3 = True:
    print("Fizz")
else if n % 5 = True:
    print("Buzz")
elif print n

Can anyone help? Thank you very much!

MatthewMartin
  • 32,326
  • 33
  • 105
  • 164
Lorenzo Battilocchi
  • 862
  • 1
  • 10
  • 26
  • 3
    maybe you mean : `n%3==0` – SerCrAsH Mar 30 '14 at 12:13
  • 6
    Ah, yes, the famous FizzBuzz test [designed to determine whether an applicant actually knows how to code](http://imranontech.com/2007/01/24/using-fizzbuzz-to-find-developers-who-grok-coding/). – Louis Mar 30 '14 at 12:21
  • 3
    The best part is how you remembered `elif` only after writing `else if`, even though the problem statement told you to remember it. – Wooble Mar 30 '14 at 12:32
  • 1
    There are many Python tutorials that will help you to get a basic understanding of the language. For example https://docs.python.org/2/tutorial/ is the official introduction. – sth Mar 30 '14 at 13:31

11 Answers11

8

A few issues with your code here. The first issue is that, for comparison, you should be using ==, not =, which is for assignment.

The second issue is that you want to check that the remainder of the divisions (which is what the modulo operator calculates) is zero, not that it's true, which doesn't really make sense.

You should be using elif for "otherwise if..." and else for "otherwise." And you need to fix the formatting of your else clause.

You want:

n=input()
if n%3 == 0:
    print("Fizz")
elif n%5 == 0:
    print ("Buzz")
else:
    print n

Finally, your code does not meet the spec:

1) If the number is divisible by both 3 and 5 print "FizzBuzz"

The above will not do this. This part I'm going to leave to you because I'm not here to solve the assignment for you :)

Ant P
  • 24,820
  • 5
  • 68
  • 105
5

Based on this

FizzBuzz: For integers up to and including 100, prints FizzBuzz if the integer is divisible by 3 and 5 (15); Fizz if it's divisible by 3 (and not 5); Buzz if it's divisible by 5 (and not 3); and the integer otherwise.

def FizzBuzz():
    for i in range(1,101):
        print {
            3 : "Fizz",
            5 : "Buzz",
            15 : "FizzBuzz"}.get(15*(not i%15) or
                                 5*(not i%5 ) or
                                 3*(not i%3 ), '{}'.format(i))

The .get() method works wonders here.

Operates as follows

For all integers from 1 to 100 (101 is NOT included),
print the value of the dictionary key that we call via get according to these rules.

"Get the first non-False item in the get call, or return the integer as a string."

When checking for a True value, thus a value we can lookup, Python evaluates 0 to False. If i mod 15 = 0, that's False, we would go to the next one.

Therefore we NOT each of the 'mods' (aka remainder), so that if the mod == 0, which == False, we get a True statement. We multiply True by the dictionary key which returns the dictionary key (i.e. 3*True == 3)

When the integer it not divisible by 3, 5 or 15, then we fall to the default clause of printing the int '{}'.format(i) just inserts i into that string - as a string.

Some of the output

Fizz
79
Buzz
Fizz
82
83
Fizz
Buzz
86
Fizz
88
89
FizzBuzz
91
92
Fizz
94
Buzz
Fizz
97
98
Fizz
Buzz

Community
  • 1
  • 1
VISQL
  • 1,960
  • 5
  • 29
  • 41
4

n % 3 (or n % any number) does not evaluate to True or False, it's not a Boolean expression. n % 3 == 0 on the other hand, does.

As an aside, what happens when n % 3 == 0 and n % 5 == 0 both evaluate to True?

rpmartz
  • 3,759
  • 2
  • 26
  • 36
  • 1
    @geoffspear is right, they are subclasses of `int` (can be checked with `isinstance(True, int)`). `True+3` is `4`, and `False*5` is `0` in Python. So checking divisibility by 3 can be done by `n%3 == 0` or `n%3 == False`, even though the latter would not be intuitive. – FatihAkici Mar 16 '18 at 16:36
3

Here's how I did it using generators. Explanations are added as comments.

# the factors to check for, along with its
# associated text data.
FACTORS = {
    3 : "Fizz",
    5 : "Buzz",
}


def fizzbuzz(start, stop):
    """FizzBuzz printer"""
    for i in range(start, stop+1):
        string = ""  # build string

        # iterate through all factors
        for j, dat in FACTORS.items():
            # test for divisibility
            if i % j == 0:
                # add data to string if divisible
                string += dat

        if not string:
            # if string's length is 0, it means,
            # all the factors returned non-zero
            # modulus, so return only the number
            yield str(i)
        else:
            # factor had returned modulo as 0,
            # return the string
            yield string


if __name__ == "__main__":
    for each in fizzbuzz(1, 100):
        print(each)

This version has the advantage of not depending on any extra factor checks.

arunanshub
  • 581
  • 5
  • 15
2

one of the shortest answers i have found is

c=1
while c<101:print((c%3<1)*'Fizz'+(c%5<1)*'Buzz'or c);c+=1

61 characters

ChrisMM
  • 8,448
  • 13
  • 29
  • 48
Breazi
  • 21
  • 1
1

Make it universal for any integer, positive or negative. Also make it easily expandable to other keywords for any integer by creating a dictionary of keywords.

def checkdict(divdict, i):
    out = ""
    for key in divdict:
        if key != 0:
            if i%key==0:
                out+=divdict[key]
        if key == 0 and i == 0:
                out+=divdict[key]
    if out == "":
        out = i
    print(out)

if __name__ == "__main__":
    mydict = {3:"Fizz",5:"Buzz"}
    for i in range(-50,50):
        checkdict(mydict, i)
  • Actually the output of this code is not well-defined: Iterating through a has no predictable order (therefore for 15 it might create 'FizzBuzz' or 'FuzzBizz') and I think this is a good example for over-engineering: It is much more general than required and adds much complexity; on the other side also the naming is not very well. – Kevin Meier Jun 12 '19 at 20:24
1
def check(num):
    finalWord = ''
    for k,v in numWordDict.items():
        if num % k == 0:
            finalWord += v

    if not finalWord:
        return num
    else: 
        return finalWord

def FizzLoop(start=0, stop=10, step=1):
    for i in range(start, stop, step):
        print(check(i))


numWordDict = {3:'fizz', 6:'buzz', 5:'fiver'}

FizzLoop(0, 10)
print("----------")
FizzLoop(0, 50, 5)
1
Numbers = [3, 5]
Labels = ["Fizz", "Buzz"] 

for i in range(1, 101):
    Output ="" 
    for j in range (len(Numbers) ) : 
        if i % Numbers[j] == 0:
            Output = Output + Labels[j]     
              
        if Output =="" :                           
             print(i) 
        else:
             print(Output)
Seljuk Gulcan
  • 1,826
  • 13
  • 24
Ineova
  • 21
  • 1
  • Thanks for the fix @Seljuk Gülcan . Ok so with this script it is very easy to just add more numbers and labels as I would hope is very easy to see. – Ineova Jul 25 '20 at 12:12
1

Nothing fancy, using a while loop to achieve the same result:

x,xx = 1,100
xy,xz = 3,5
mylist = []

while x <= xx:
    y = (x/xy).is_integer()
    z = (x/xz).is_integer()

    if y and z:
        mylist.append("fizzbuzz")
    elif y:
        mylist.append("fizz")
    elif z:
        mylist.append("buzz")
    else:
        mylist.append(x)
    x+=1

print(mylist)
0

Please find the 1 liner code (list comprehension) code below. Hope this is easy to understand . if it's not please do let me know. I will elaborate.

N = 10 #user_input
print(list(map(lambda n: "Fizz" if (n % 3 == 0) else ( "Buzz" if (n % 5 == 0) else n),[i for i in range(1,N+1)])))
VMSMani
  • 416
  • 4
  • 7
0
def fizz_buzz(input):
  if (input % 3 == 0) and (input % 5 == 0):
     return "FizzBuzz"
  if input % 3 == 0:
     return "Fizz"
  if input % 5 == 0:
     return "Buzz"
  return input


print(fizz_buzz(15))
Art
  • 2,836
  • 4
  • 17
  • 34