Python 练习实例23

简介: Python 练习实例23

题目:打印出如下图案(菱形):

  *

 ***

*****

*******

*****

 ***

  *

程序分析:先把图形分成两部分来看待,前四行一个规律,后三行一个规律,利用双重for循环,第一层控制行,第二层控制列。

程序源代码:

实例

#!/usr/bin/python# -*- coding: UTF-8 -*- from sys import stdoutfor i in range(4):     for j in range(2 - i + 1):         stdout.write(' ')    for k in range(2 * i + 1):         stdout.write('*')    print('') for i in range(3):     for j in range(i + 1):         stdout.write(' ')    for k in range(4 - 2 * i + 1):         stdout.write('*')    print('')

实例(Python3)

def print_diamond(rows):

   # 上半部分

   for i in range(1, rows, 2):

       spaces = " " * ((rows - i) // 2)

       stars = "*" * i

       print(spaces + stars)


   # 下半部分

   for i in range(rows, 0, -2):

       spaces = " " * ((rows - i) // 2)

       stars = "*" * i

       print(spaces + stars)


# 设置行数,可以根据需要调整

rows = 7

print_diamond(rows)

以上实例输出结果为:

  *

 ***

*****

*******

*****

 ***

  *

相关文章
|
1天前
|
Python
Python 练习实例30
Python 练习实例30
|
1天前
|
Python
Python 练习实例29
Python 练习实例29
|
2天前
|
Python
Python 练习实例27
Python 练习实例27
|
2天前
|
Python
Python 练习实例26
Python 练习实例26
|
2天前
|
Python
Python 练习实例25
Python 练习实例25
|
1天前
|
Python
Python 练习实例28
Python 练习实例28
|
2天前
|
数据安全/隐私保护 Python
经验大分享:python练习:从番号到封面
经验大分享:python练习:从番号到封面
|
3天前
|
数据安全/隐私保护 Python
经验大分享:python练习:从番号到封面
经验大分享:python练习:从番号到封面