python怎么打印菱形-Python教程

资源魔 39 0

python怎样打印菱形?上面给各人带来三种办法:

第一种

rows = int(input('请输出菱形边长:\n'))
row = 1
while row <= rows:
    col = 1     # 保障每一次内轮回col都从1开端,打印后面空格的个数
    while col <= (rows-row):  # 这个内层while就是单纯打印空格
        print(' ', end='')  # 空格的打印没有换行
        col += 1
    print(row * '* ')  # 每一一行打印完空格后,接着正在同一行打印星星,星星个数与行数相等,且打印完星星后print默许换行
    row += 1
 
bottom = rows-1
while bottom > 0:
    col = 1     # 保障每一次内轮回col都从1开端,打印后面空格的个数
    while bottom+col <= rows:
        print(' ', end='')  # 空格的打印没有换行
        col += 1
    print(bottom * '* ')  # 每一一行打印完空格后,接着正在同一行打印星星,星星个数与行数相等,且打印完星星后print默许换行
    bottom -= 1

输入后果:

请输出菱形边长:
5
    * 
   * * 
  * * * 
 * * * * 
* * * * * 
 * * * * 
  * * * 
   * * 
    *

相干保举:《Python视频教程》

第二种

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))

输入后果:

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

第三种

def stars(n):
    RANGE1 = [2*i+1 for i in range(n)]
    RANGE2 = [2*i+1 for i in range(n)[::-1]][1:]
    RANGE = RANGE1 + RANGE2
    RANGE_1 = [i for i in range(n)[::-1]]
    RANGE_2 = [i for i in range(n)[1:]]
    RANGE_12 = RANGE_1 + RANGE_2
    for i in range(len(RANGE)):
        print (' '*RANGE_12[i] + '*'*RANGE[i])
if __name__ ==  "__main__":
    stars(5)

输入后果:

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

以上就是python怎样打印菱形的具体内容,更多请存眷资源魔其它相干文章!

标签: python教程 python编程 python使用问题 python怎么打菱形

抱歉,评论功能暂时关闭!