我是python的新手,请有人帮助绘制如下形状。该程序必须以星号作为输入。

星数= 7

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


我的代码:

count = int(input('star count : '))
pattern_size = count + 1
for t in range(1, pattern_size):
    pattern = list(" " * pattern_size)
    pattern[:t] = "*" * t
    pattern[-t:] = '*' * t
    print(''.join(pattern))

star count :  9
*        *
**      **
***    ***
****  ****
**********
**********
**********
**********
**********

最佳答案

这是一个易于理解的示例,该方法在您的方法中使用了两个for循环:一个正好相反

count = int(input('star count : '))
pattern_size = count + 1
for t in range(1, int(pattern_size/2)):
    pattern = list(" " * pattern_size)
    pattern[:t] = "*" * t
    pattern[-t:] = '*' * t
    print(''.join(pattern))

for t in range(int(pattern_size/2), 0, -1):
    pattern = list(" " * pattern_size)
    pattern[:t] = "*" * t
    pattern[-t:] = '*' * t
    print(''.join(pattern))


还有一个更高级的方法是像这样使用字符串方法.center()

count = int(input('star count : '))
pattern_size = count + 1
for t in range(1, int(pattern_size/2)):
    print((" " * (pattern_size-t*2)).center(pattern_size, '*'))
for t in range(int(pattern_size/2), 0, -1):
    print((" " * (pattern_size - t * 2)).center(pattern_size, '*'))

10-01 10:44