Muhammad Jafar Muhammad Jafar - 1 year ago 55
Python Question

A better code to make an empty square with using numbers

hi i want to make an empty square with numbers and i have the code like this:

L = input ('input your numbers = ')
M = (L-2) * ' '
P = L - 1
x = ""
y = ""

for a in range(1,L+1):
x = x + str(a)
print x
for b in range(2,L):
print str(b) + M + str(P)
for c in range(L,0,-1):
y = y + str(c)
print y

i just want to know if you guys can help me with the better code.. idk i just feel not satisfied enough with my code.. maybe you can give me an alternative ways (add some condition or maybe create increment and decrement number only use 1 function ?)
btw this is the first time to ask in here hehe


Answer Source

Not exactly the same output as yours (due to print placing space after each digit), but example how to accomplish the same by detecting edge and calculating value:

n = input('> ')
m = n-1

for i in range(n):
    for j in range(n):
        if i == 0 or j == 0:   # top or left edge
            print 1+i+j,
        elif i == m or j == m: # right or bottom edge
            print 2*n-1-i-j ,
        else:                  # inside
            print ' ',