Reputation: 27
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
Upvotes: 0
Views: 865
Reputation: 54148
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])
Upvotes: 0
Reputation: 11337
size = int(input("size? : "))
for i in range(size):
for j in range(i*size, i*size+size):
print(j, end=" ")
print()
Upvotes: 1