One approach is to continue your work with a second for loop. Also, note that there is no need for the else: pass
clause.
n = 5
d = n
for x in range(1, n + 1):
for y in range(1, n * 2 + 1):
if (y >= d) != 0 and y <= n + x - 1:
print(x * y, end=" ")
elif y <= n:
print(" ", end=" ")
d -= 1
print()
d+=2
for x in range(n+1, 2*n):
for y in range(1, n * 2 + 1):
if (y >= d) != 0 and y <= 3*n - x-1:
print(x * y, end=" ")
elif y <= n:
print(" ", end=" ")
d += 1
print()
Which results in this output:
5
8 10 12
9 12 15 18 21
8 12 16 20 24 28 32
5 10 15 20 25 30 35 40 45
12 18 24 30 36 42 48
21 28 35 42 49
32 40 48
45
On the other hand, you might appreciate this script, which takes advantage of the str.format
method.
n = 5
d = n
form = '{0:<4}'
rows = [[' '*4 for _ in range(2*n)] for _ in range(2*n)]
for x in range(1,n):
for y in range(d,n+x):
rows[x][y] = form.format(x*y)
d-=1
for x in range(n, 2*n):
for y in range(d, 3*n - x):
rows[x][y] = form.format(x*y)
d+=1
for row in rows:
print(''.join(row))
Here's the resulting output:
5
8 10 12
9 12 15 18 21
8 12 16 20 24 28 32
5 10 15 20 25 30 35 40 45
12 18 24 30 36 42 48
21 28 35 42 49
32 40 48
45
You might find it interesting to see how the outputs change as n is varied.
We could also get the same result as the above without the d
parameter:
n = 5
form = '{0:<4}'
rows = [[' '*4 for _ in range(2*n+1)] for _ in range(2*n+1)]
for x in range(1,n):
for y in range(n-x+1,n+x):
rows[x][y] = form.format(x*y)
for x in range(n, 2*n):
for y in range(x-n+1, 3*n - x):
rows[x][y] = form.format(x*y)
for row in rows:
print(''.join(row))