Search code examples
pythonloopsnested-loops

Python Nested Loop number pattern outputting additional line?


I am trying to create a number grid specifically using for loops. My code is as follows

def draw_grid (num):#x represents row y representes column
for x in range (num):
    print(x+1, end= ' ' )
    print()
    for y in range (num):
        print(y+1, end= ' ' )

And my ouput results as this when I draw a grid of 10 for example. 1 1 2 3 4 5 6 7 8 9 10 2 1 2 3 4 5 6 7 8 9 10 3 1 2 3 4 5 6 7 8 9 10 4 1 2 3 4 5 6 7 8 9 10 5 1 2 3 4 5 6 7 8 9 10 6 1 2 3 4 5 6 7 8 9 10 7 1 2 3 4 5 6 7 8 9 10 8 1 2 3 4 5 6 7 8 9 10 9 1 2 3 4 5 6 7 8 9 10 10 1 2 3 4 5 6 7 8 9 10

I have tried manipulating it several different ways but I cannot discern what is creating the 1 at the top and the 2-10 on the rightmost column? Should my Y value be coded differently?


Solution

  • Here is what is happening

    def draw_grid (num):#x represents row y representes column
        for x in range (num):
            print(x+1, end= ' ' )
            print()
            for y in range (num):
                print(y+1, end= ' ' ) 
    

    In your outer loop you are printing x + 1 on every iteration with no newline, end = ' ' and then printing a new line, print(). On your first iteration its printing 1 with no newline followed by a newline from print() and then it enters your inner loop and is printing 1-10 again with no new line at the end. Now when the second iteration of your outer loop occurs it prints 2, that's going to be printed right after all the y values followed by print() and the process repeats.

    What you want is this most likely

    def draw_g(num):
        for x in range(num):
            for y in range(num):
                print(y + 1, end = ' ')
            print()
    
    draw_g(10)
    

    Here we are only using our outer loop to determine the amount of rows, times we will print all the values in our inner loop. For our first iteration we print all the values of y + 1 in range(num) once that is completed we use print() to advance to the next line and then the second iteration of of outer loop takes place, this repeats for x in range(num) . And the result is this.

    1 2 3 4 5 6 7 8 9 10 
    1 2 3 4 5 6 7 8 9 10 
    1 2 3 4 5 6 7 8 9 10 
    1 2 3 4 5 6 7 8 9 10 
    1 2 3 4 5 6 7 8 9 10 
    1 2 3 4 5 6 7 8 9 10 
    1 2 3 4 5 6 7 8 9 10 
    1 2 3 4 5 6 7 8 9 10 
    1 2 3 4 5 6 7 8 9 10 
    1 2 3 4 5 6 7 8 9 10