如下所示:
1
2
3
4
5
6
7
8
9
10
|
a = int ( input ( "请输入菱形行数:" ))
m = a #空格
d = a #倒三角
for i in range ( 1 , a + 1 ): # 先打印正三角
print ( " " * (m - 1 ), "*" * ( 2 * i - 1 )) #2个*参数: 第一个是:空格 第二个是: *根据规律组成
m - = 1
if i = = a: # 临界点,开始打印倒三角
for y in range ( 1 , a):
print ( " " * y, "*" * ( 2 * d - 3 )) #2个*参数: 第一个是:空格 第二个是: *根据规律组成
d - = 1 #设置-1
|
1
2
3
4
5
6
7
8
9
10
|
a = 4 #指定行数
b = a #空格
c = a #倒三角
for i in range ( 1 ,a + 1 ):
print ( " " * (b - 1 ), "%d" % b * ( 2 * i - 1 ))
b - = 1
if i = = a: # 临界点,开始打印倒三角
for y in range ( 1 ,a):
print ( " " * y, "%d" % (y + 1 ) * ( 2 * c - 3 ))
c - = 1
|
1
2
3
4
5
6
7
8
9
10
11
12
|
a = int ( input ( "请输入菱形行数:" ))
m = a #空格
d = a #倒三角
print ( " " * (a - 1 ), "*" ) #第一个是:空格, 第二个是:打印一个*
for i in range ( 2 , a + 1 ): # 先打印正三角
print ( " " * (m - 1 ) + "*" + " " * ( 2 * i - 3 ) + "*" ) #1个*参数: 第一个是:空格和*根据规律组成
m - = 1
if i = = a: # 临界点,开始打印倒三角
for y in range ( 2 , a):
print ( " " * y + "*" + " " * ( 2 * d - 5 ) + "*" ) #1个*参数: 第一个是:空格和*根据规律组成
d - = 1 #设置-1
print ( " " * a + "*" ) #打印最后一个*
|
补充知识:使用Python打印一些图形,主要是找到循环规律
打印菱形
1
2
3
4
5
6
|
a = int ( input ())
e = a / / 2
for i in range (e, - 1 , - 1 ):
print ( ' ' * i, '*' * (a - 2 * i), ' ' * i)
for i in range ( 1 ,e + 1 ):
print ( ' ' * i, '*' * (a - 2 * i), ' ' * i)
|
改进版本,找到规律,使用abs函数
1
2
3
4
5
|
a = int ( input ( '>>>' ))
e = a / / 2
for i in range ( - e, e + 1 ):
j = abs (i)
print ( ' ' * j + '*' * (a - j * 2 ) + ' ' * j)
|
打印对顶三角
1
2
3
4
5
6
|
a = int ( input ( '>>>' ))
e = a / / 2
for i in range (e + 1 ):
print ( ' ' * i, (a - i * 2 ) * '*' , ' ' * i, sep = '')
for i in range ( 1 , e + 1 ):
print ( ' ' * (e - i), (i * 2 + 1 ) * '*' , ' ' * (e - i), sep = '')
|
倒三角的打印,可以不用考虑*后面的空格,其实可以简化
1
2
3
4
5
|
a = int ( input ( '>>>' ))
e = a / / 2
for i in range ( - e, e + 1 ):
j = abs (i)
print ( ' ' * (e - j) + '*' * (j * 2 + 1 ))
|
打印一道闪电:
按照最笨的思路分三部分打印
1
2
3
4
5
6
7
|
a = int ( input ( '>>>' ))
e = a / / 2
for i in range ( - e, 0 ):
print ( ' ' * abs (i) + '*' * (a - e - abs (i)))
print ( '*' * a)
for i in range ( 1 , a - e):
print ( ' ' * e + '*' * (a - e - i))
|
稍作改进
1
2
3
4
5
6
7
8
9
|
a = int ( input ( '>>>' ))
e = a / / 2
for i in range ( - e, a - e):
if i < 0 :
print ( ' ' * abs (i) + '*' * (a - e - abs (i)))
elif i > 0 :
print ( ' ' * e + '*' * (a - e - i))
else :
print ( '*' * a)
|
打印正方形
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
for i in range (n):
sepTop + = '\t*'
sepMid + = '\t'
else :
sepMid + = '*'
print (sepTop)
for i in range (n - 1 ):
print ( '\n' )
print (sepMid)
else :
print ( '\n' )
print (sepTop)
print ( '=====================================' )
e = - n / / 2
for i in range (e,n + e):
if i = = e or i = = n + e - 1 :
print ( '*' * n)
else :
print ( '*' + ' ' * (n - 2 ) + '*' )
print ( '=====================================' )
|
以上这篇Python 使用双重循环打印图形菱形操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/hlx20080808/article/details/107576443