Search code examples
pythonsizespaces

Drawing a square with "." and " " only in Python


I am trying to make a square with spaces and dots only, but I am having an issue. I need to make the code in that way, so I can change the size of the square in just 1 input for each parameter. I am having issues with the "sides" variable how can I make the space between left side and right side automated by just giving only 1 input value.

def square_shape(top,sides,bottom):
            top = ". "*top
            sides =((".")+("     .\n"))*sides
            bottom = ". "*bottom
            print top
            print sides,bottom
        square_shape(8,7,8)

P.S With this code it works perfectly fine, but when I change the size of top and bottom , the space needed is not created in the sides. I hope I was clear.

Thank you in advance


Solution

  • Make the space being dependent on length of square and don't use \n in the string or else your last line will also print a newline -

    def square_shape(leng): # no need to use 3 variables
            print (". "*leng)
            for _ in range(leng-2):
                print (". " + "  " * (leng - 2) + ".")
            print (". "*leng)
    square_shape(8)
    

    Output -

    . . . . . . . . 
    .             .
    .             .
    .             .
    .             .
    .             .
    .             .
    . . . . . . . .