Search code examples
pythonpython-3.xfizzbuzz

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

fizzbuzz(20) 

would print 1,2,fizz,4,buzz,fizz,7,8,fizz,buzz,11,fizz,13,14,fizzbuzz,16,17,fizz,19,buzz

def fizzbuzz(n):

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

def main():
  print(fizzbuzz(20))

Solution

  • 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:
                result.append('fizz')
            elif x % 5 == 0:
                result.append('buzz')
            else:
                result.append(str(x))
        return result
    
    def main():
        print(', '.join(fizzbuzz(20)))
    
    main()
    

    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.