用“。”画一个正方形。和“”仅在Python中

时间:2017-03-10 17:09:18

标签: python size spaces

我正在尝试制作一个只有空格和圆点的正方形,但我遇到了问题。 我需要以这种方式制作代码,因此我可以在每个参数的1个输入中更改方块的大小。我遇到“侧面”变量的问题如何通过仅提供1个输入值来使左侧和右侧之间的空间自动化。

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使用此代码可以很好地工作,但是当我更改顶部和底部的大小时,所需的空间不会在侧面创建。 我希望我很清楚。

提前谢谢

3 个答案:

答案 0 :(得分:1)

使空间取决于方形长度,不要在字符串中使用\n,否则最后一行也会打印换行符 -

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)

输出 -

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

答案 1 :(得分:0)

这个怎么样?

def square_shape(size):
    print '. ' * size + '.'
    print ('.' + '  ' * (size-1) + ' .\n') * (size-1),
    print '. ' * size + '.'

答案 2 :(得分:0)

小幅优化!

square_shape = int(input())
print ("."*square_shape)
for _ in range(square_shape-2):
    print ("."+ " "*(square_shape-2) + ".")
print ("."*square_shape)