如何在Python中使用for循环从星号制作一个盒子或矩形

时间:2018-10-04 15:38:49

标签: python

到目前为止,我只编写了第一部分的代码,现在我被困住了,如何将其显示在输出中。示例为height = 5 and width = 9

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

根据输入的数字显示哪个,这是代码:

width=int(input('Input the width: '))
height=int(input('Input the height: '))
long=0
for vertical in range(height):
    print('*')

我尝试了几种方法,请帮忙。我被困在这里,对此感到沮丧。

4 个答案:

答案 0 :(得分:1)

逐步:

# top row:             *********
print('*' * width)

# "side walls":        *       *
for _ in range(height - 2):
    print('*' + ' ' * (width - 2) + '*')

# bottom row           *********
print('*'*width)

答案 1 :(得分:0)

您可以为height的第一个和最后一个索引设置条件以打印'*' * w,然后在两个索引之间的条件将打印'*' + ' '*(w - 2) + '*'

w = 9
h = 5

for i in range(h):
    if not i or i == h-1:
        print('*'*w, end ='')
        print()
    else:
         print('*' + ' '*(w-2) + '*')
*********
*       *
*       *
*       *
*********

答案 2 :(得分:0)

您可以这样:

h = 5
w = 9

for l in range(h):
    if l % (h-1) == 0:
        print('*' * w)
    else:
        print('*' +' ' * (w-2) + '*')

答案 3 :(得分:0)

Python定义了字符串的乘法运算符,

>>> '*' * 9
'*********'

此功能使您的代码更容易执行。

def asterisk_box(width, height):
    'Create a box of asterisks and return it as a string'
    assert height >= 2  # Make sure we actually have a box
    assert width >= 2   # Make sure we actually have a box
    box = '*' * width + '\n'
    for _ in range(height - 2):
        box += '*' + ' ' * (width - 2) + '*\n'
    box += '*' * width
    return box

print(asterisk_box(9, 5))

此输出

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

如果您想在框中输入文本会变得有些困难,但也不太糟糕。

def asterisk_message(width, height, message):
    'Put a message within the asterisk box'
    assert height >= 3                # Make sure there is room for a message
    assert len(message) <= width - 2  # Make sure the box is wide enough
    box = asterisk_box(width, height)
    box = box.splitlines()
    row = height // 2
    box[row] = '*' + message.center(width - 2) + '*'
    return '\n'.join(box)

print(asterisk_message(9, 5, 'hello'))

此输出

*********
*       *
* hello *
*       *
*********