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)

以上实例输出结果为:

  *

 ***

*****

*******

*****

 ***

  *

相关文章
|
3天前
|
Python
Python 练习实例94
Python 练习实例94
|
3天前
|
Python
Python 练习实例92
Python 练习实例92
|
3天前
|
Python
Python 练习实例93
Python 练习实例93
|
2天前
|
Python
Python 练习实例97
Python 练习实例97
|
2天前
|
Python
Python 练习实例96
Python 练习实例96
|
4天前
|
Python
Python 练习实例90
Python 练习实例90
|
4天前
|
数据安全/隐私保护 Python
Python 练习实例89
Python 练习实例89
|
4天前
|
Python
Python 练习实例91
Python 练习实例91
|
2天前
|
Python
Python 练习实例95
Python 练习实例95
|
3天前
|
Python
Python中类属性与实例属性的区别
了解这些区别对于编写高效、易维护的Python代码至关重要。正确地使用类属性和实例属性不仅能帮助我们更好地组织代码,还能提高代码运行的效率。
6 0