Python3练习题 018:打印星号菱形

时间:2024-10-06 11:05:20

Python的内置方法 str.center(width [, fillchar]) 就能轻而易举打印出来:str即是数量不等的星号,width即是最大宽度(7个空格),默认填充字符fillchar就是空格。两个for循环搞定!代码如下:

1
2
3
4
5
s = '*'
for i in range(1, 8, 2):
    print((s*i).center(7))
for i in reversed(range(1, 6, 2)):
    print((s*i).center(7))

方法二

s = '*'
for i in range(1,8,2):
    t = (7-i)//2
    print(' '*t + s*i + ' '*t)
for i in reversed(range(1,6,2)):
    t = (7-i)//2
    print(' '*t + s*i + ' '*t)