0

I used two for loops for this and i stuck in here;

size = int(input("size? : "))

matrix = list(range(size**2))

for i in range(size):
    for j in range(size):
        print(j, end=" ")
     print()

and my output is;

size? : 3
0 1 2 
0 1 2 
0 1 2 

How can I make it look like;

0 1 2
3 4 5
6 7 8

But it has to be work for any number that i gave

2 Answers 2

1
size = int(input("size? : "))

for i in range(size):
    for j in range(i*size, i*size+size):
        print(j, end=" ")
    print()
Sign up to request clarification or add additional context in comments.

2 Comments

Is there any way that I can make output of numbers centered. For example when I make the size 4 last two rows are moving right.
yes, replace the 4th line with print('%3d' % j, end=" ")
0

You can't expect to print values from 0-9 without using the matrix variable, you just print j everytime which is range of size, that's normal, you may use matrix :

for i in range(size):
    for j in range(size):
        print(matrix[i * size + j], end=" ") 
        # print(f'{matrix[i * size + j]:>2d}', end=" ") to format 2 digit numbers
    print()

This also works

for idx in range(0, len(matrix), size):
    print(*matrix[idx:idx + size])

2 Comments

Thank you very much. That helped a lot. And I have also a follow-up question. Is there any way that I can make output of numbers centered. For example when I make the size 4 last two rows are moving right.
@SamFatu I've just edit for this, the '2' in >2d means 'padd befor with space to reach size of 2 at all, so if you have 3 digits at a moment use '3'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.