Search code examples
pythonfor-loopsquare

how to make a square in python


k=int(input('n:'))
def square(n):
    lines = ['*' * (n - i) + " " * i for i in range(n)]
    for l in lines + lines[-2::-1]:
        print(l + l[::-1])
square(k)

I'm making a code that prints squares with stars. If I put 2 in n the square has to be a 3x3 square but it prints 4x3 square. And if i put 4 in n there has to be a 7x7 square but it prints 8x7 square. The blank square in the middle has to have n numbers of stars on each side. where do I have to change to fix this problem?


Solution

  • You need a special case for the top and bottom lines, where you need one less star.

    (This is because if you watch the pattern, it's almost like the center star has two overlapped stars on top of each other, which reduces one visible star)

    Here's how I'd write it:

    def print_line(n, i, gap):
        if i == 0:
            print('*' * (2*n-1))
        else:
            print('*' * (n-i) + ' ' * (gap-1) + '*' * (n-i))
    
    def square(n):
        gap = 0
        for i in range(n):
            print_line(n, i, gap)
            gap += 2
    
        gap = 2*n - 4
        for i in reversed(range(n-1)):
            print_line(n, i, gap)
            gap -= 2
    
    
    square(10)