user2715061 user2715061 - 3 months ago 18x
Python Question

Trying to turn fizzbuzz into a function in python 3

I have only just started to learn python as my first language and whilst i worked out the code for fizzbuzz, i cannot for the life of me get it to do the items below. I also want it to print horizontally instead of vertically. Any help would be great (heads spinning).
Create a function which does this.
For example


would print

def fizzbuzz(n):

for x in range (101):
if x%3==0 and x%5==0:
print("fizz buzz")
elif x%3==0:
elif x%5==0:
print (x)

def main():


Collect the items into a list. Then print the list at the end of function. You can join the items together with a comma in between using ', '.join(...).

def fizzbuzz(n):
    result = []
    for x in range(1, n+1):
        if x % 3 == 0 and x % 5 == 0:
            result.append("fizz buzz")
        elif x % 3 == 0:
        elif x % 5 == 0:
    return result

def main():
    print(', '.join(fizzbuzz(20)))


It's good to also know that print(..., end=', ') would print "horizontally" with a comma and space at the end, and this would almost solve your problem except that the very last item would also have a comma and space at the end, which is not what you desire.

It's usually a good idea to (1) separate printing from computing, (2) make functions reusable. You often want to compute more frequently than print. In the future you may wish to pass the computation on to some other function before you print. So functions that immediate print are not as useful. So I recommend taking the print statements out of fizzbuzz.

You could return the string ', '.join(result), but how useful would that be? The list result might be (in the future) more useful for further processing, so I chose to return result. The printing I left for the main function.