最近刚开始学习Python,刚学了一些语法和循环控制语句等等基础,自己练习打印了一个菱形,最简单就是两个独立的for循环,一个打印上半部分,一个打印下半部分,我加了个条件判断,用一个独立的嵌套for循环打印出来了。记下笔记,作为自己学习的一个记录。
for i in range(1, 22, 2):
spacecount = (11-i)//2
spaceList = range(spacecount)
starList = range(i)
if spacecount < 0:
spaceList = range(abs(spacecount))
starList = range(22-i)
for j in spaceList:
print(' ', end='')
for k in starList:
print('*', end='')
print()
输出
=================== RESTART: D:/Projects/python/diamond.py ===================
*
***
*****
*******
*********
***********
*********
*******
*****
***
*
>>>
写成一个函数,可以打印任意大小的菱形:
def diamond(n):
for i in range(1, n, 2):
spacecount = (n//2-i)//2
spaceList = range(spacecount)
starList = range(i)
if spacecount < 0:
spaceList = range(abs(spacecount))
starList = range(n-i)
for j in spaceList:
print(' ', end='')
for k in starList:
print('*', end='')
print()