Amatuer Ayers
Amatuer Ayers

Reputation: 39

Python, nested loops print on one line, multiple copies

Very new to python so please excuse!

question is...to make an output look like

1 2 3 4 5

1 2 3 4 5

1 2 3 4 5

I am using user input for the limit and the number of copies ( in this example 5 and 3), so I have done this;

limit = int(input("Select upper limit"))
copies = int(input("Select number of copies"))


def output(limit):
    for i in range(copies):
        for x in range(limit):
            print (x + 1, end=" ")


output(limit)

However the answer shows up as 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5. I know it's because of the end=" " but not sure how to get around it! Any help appreciated

Upvotes: 1

Views: 5300

Answers (4)

Ulrich Eckhardt
Ulrich Eckhardt

Reputation: 17415

You got the part with the ranges correctly, but there's one thing you missed, you can specify a starting number:

v0 = range(1, limit + 1)

In order to convert a number to a string, use the str() function:

v1 = (str(x) for x in v0)

In order to put a space between adjacent numbers, use the string's join() memberfunction:

v2 = ' '.join(v1)

Then, you could either add the linebreaks yourself:

v3 = (v2 + '\n') * copies
print(v3, end='')

Alternatively in this form:

v3 = '\n'.join(v2 for i in range(copies))
print(v3)

Or you just print the same line multiple times in a plain loop:

for i in range(copies):
    print(v2)

BTW: Note that v0 and v1 are generators, so joining them into a string v2 will change their internal state, so you can't simply repeat that and get the same results.

Upvotes: 3

V Sree Harissh
V Sree Harissh

Reputation: 663

limit = int(input("Select upper limit"))
copies = int(input("Select number of copies"))

def output(limit):
    for i in range(copies):
        if (i!=0):
            print()
            print()
        for x in range(limit):
            print (x + 1, end="")

output(limit)

Upvotes: 0

Saksham Varma
Saksham Varma

Reputation: 2130

Just a little modification to your code:

def output(limit):
    for i in range(copies):
        for x in range(limit):
            print(x + 1, end=' ')
        print()

Upvotes: 0

falsetru
falsetru

Reputation: 368904

Print new line explicitly for every loop:

def output(copies, limit):
    for i in range(copies):
        for x in range(limit):
            print (x + 1, end=" ")
        print()  # <----
        # print()  # Add this if you want an empty line

output(copies, limit)

Upvotes: 3

Related Questions