Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (50.2k points)

I am currently working on the code for fizzbuzz. In that, I want to print horizontally instead of vertically. And I want to perform that in a user-defined function:

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))

1 Answer

0 votes
by (107k points)

First, try to store all the elements into a list. Then print the list at the end of the method. 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()

In Python, we have one attribute named end in the print statement that will help you to print your elements horizontally with some space in the end. And I think, with that, it will nearly 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.

Related questions

0 votes
1 answer
0 votes
4 answers
0 votes
2 answers

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...