Search code examples
pythonstringpython-3.xline-breaks

Stuck on where to insert a line break when there are no quotation marks


I'v done a code challenge and one of the extras was write a line of code that prints the previous result (which I have done)

print(str(year)*int(number))

but it also says to put a line break between each returned value. So for example the var 'year' returns an int and that int gets printed a certain amount of times depending on what the users input is.

I just can't figure out where the '\n' will go in this line of code.

 print(str(year)*int(number)) 

Solution

  • You could use a simple loop:

    for _ in range(number):
        print(year)
    

    This will insert the \n by default - as each print is a seperate command and the default end=\n parameter to print applies.

    Patrick Haugh beat me by 50sec to use the print-commands parameter sep that lets you specify what to put between printed values:

    print(1,2,3,4,sep="\n") 
    

    This prints a newline between each of the numbers - by default it prints a single space.

    You could put the collected numbers in a list, decomposit the list in its element and print them with a \n seperator:

    year = 18
    number= 3
    print( *[year]*number ,sep="\n")
    

    More can be found in the