我是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
* *
** **
*** ***
**** ****
**********
**********
**********
**********
**********
答案 0 :(得分:2)
这是一个易于理解的示例,使用您的方法使用两个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, '*'))
答案 1 :(得分:1)
就像我的评论一样,这是完整的代码:
count = int(input('star count : '))
pattern_size = count + 1
for t in range(1, pattern_size):
pattern = list(" " * pattern_size)
len_t = t if t <= (pattern_size / 2) else (pattern_size - t)
pattern[:len_t] = "*" * len_t
pattern[-len_t:] = '*' * len_t
print(''.join(pattern))
希望得到这个帮助。