当前位置:Gxlcms > Python > python怎么打印菱形

python怎么打印菱形

时间:2021-07-01 10:21:17 帮助过:21人阅读

python怎么打印菱形?下面给大家带来三种方法:

第一种

  1. rows = int(input('请输入菱形边长:\n'))
  2. row = 1
  3. while row <= rows:
  4. col = 1 # 保证每次内循环col都从1开始,打印前面空格的个数
  5. while col <= (rows-row): # 这个内层while就是单纯打印空格
  6. print(' ', end='') # 空格的打印不换行
  7. col += 1
  8. print(row * '* ') # 每一行打印完空格后,接着在同一行打印星星,星星个数与行数相等,且打印完星星后print默认换行
  9. row += 1
  10. bottom = rows-1
  11. while bottom > 0:
  12. col = 1 # 保证每次内循环col都从1开始,打印前面空格的个数
  13. while bottom+col <= rows:
  14. print(' ', end='') # 空格的打印不换行
  15. col += 1
  16. print(bottom * '* ') # 每一行打印完空格后,接着在同一行打印星星,星星个数与行数相等,且打印完星星后print默认换行
  17. bottom -= 1

输出结果:

  1. 请输入菱形边长:
  2. 5
  3. *
  4. * *
  5. * * *
  6. * * * *
  7. * * * * *
  8. * * * *
  9. * * *
  10. * *
  11. *

相关推荐:《Python视频教程》

第二种

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

输出结果:

  1. *
  2. ***
  3. *****
  4. *******
  5. *****
  6. ***
  7. *

第三种

  1. def stars(n):
  2. RANGE1 = [2*i+1 for i in range(n)]
  3. RANGE2 = [2*i+1 for i in range(n)[::-1]][1:]
  4. RANGE = RANGE1 + RANGE2
  5. RANGE_1 = [i for i in range(n)[::-1]]
  6. RANGE_2 = [i for i in range(n)[1:]]
  7. RANGE_12 = RANGE_1 + RANGE_2
  8. for i in range(len(RANGE)):
  9. print (' '*RANGE_12[i] + '*'*RANGE[i])
  10. if __name__ == "__main__":
  11. stars(5)

输出结果:

  1. *
  2. ***
  3. *****
  4. *******
  5. *********
  6. *******
  7. *****
  8. ***
  9. *

以上就是python怎么打印菱形的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行