Python 3 - 空心矩形

时间:2014-04-03 18:19:38

标签: python-3.x

我有一个作业,我们必须编写一个模块来创建某些空心形状,然后在作业中使用它们。我对矩形中最后一列的对齐有轻微问题。

我的代码是:

height = eval(input("Enter the height:\n"))

width = eval(input("Enter the width:\n"))

gap=" "

def print_rectangle(height, width):
    for i in range(height):
        if i == 0 or i == height-1:
            print(width*'*')
        else: 
            print('*' + gap*width +'*')   


print_rectangle(height,width) 

打印哪些:

****** 
*      *
*      *
*      *
*      *
*      *
*      *
*      *
******

任何可以正确排列的提示都会被赞赏:):

******
*    *
*    *
*    *
*    *
*    *
*    *
*    *
******

1 个答案:

答案 0 :(得分:1)

print('*' + gap*width +'*')

这将打印一行大小为width+2的行。 width个空格和两颗星。 如果您希望该行的大小为width,则打印两个空格。

print('*' + gap*(width-2) +'*')