Search code examples
pythonfor-loopnested-loops

How to 'enter' every n number in a nested for loop using python


I am trying to write a python function with two for loops(one nested) and accept n number and form a grid. So far, I have this code and just need to be able to essentially 'enter' after the loop has ran through to n number.

def draw_grid(n):
for i in range(1,n+1,+1):
    for j in range(1,n+1,+1):#(1,n+1,+1) starts at 1, ends at n + 1, adds in increments of 1  
        print(j, end=' ')

draw_grid(3)

prints:

1 2 3 1 2 3 1 2 3

goal:

1 2 3

1 2 3

1 2 3

so if I changed n to equal 5 it would then 'enter' every 5th number. I have tried playing around with using end=' ' in different positions to get that to work but it just changes the way individual numbers are spaced, not every n number.


Solution

  • You need to add a print() statement after the nested for loop.

    def draw_grid(n):
    for i in range(1,n+1,+1):
        for j in range(1,n+1,+1):#(1,n+1,+1) starts at 1, ends at n + 1, adds in increments of 1  
            print(j, end=' ')
        print()
    
    draw_grid(3)