用python打印空心金字塔、空心菱形
思想:化繁为简,先死后活
1.用for循环实现
def hollow_pyramid(level):
for i in range(1, level + 1):
for k in range(level - i):
print(' ', end='')
for j in range(0, 2 * i - 1):
if j == 0 or j == 2 * (i - 1) or i == level:
print("*", end='')
else:
print(" ", end='')
print()
def hollow_diamond(level):
for i in range(1, level + 1):
if i <= (level + 1) / 2:
for k in range(level - i):
print(' ', end='')
for j in range(0, 2 * i - 1):
if j == 0 or j == 2 * (i - 1):
print("*", end='')
else:
print(" ", end='')
print()
else:
for k in range(i - 1):
print(' ', end='')
for j in range(0, 2 * (level - i) + 1):
if j == 0 or j == 2 * (level - i):
print("*", end='')
else:
print(" ", end='')
print()
hollow_pyramid(11)
hollow_diamond(11)
2.用while实现
打印实心的金字塔(因为空心和实心区别主要在于j的取值,和上面思路一致,所以不在赘述,兄弟们可以自己试一试改成空心)
- 先死,5行金字塔为例
i = 1
while i <= 5:
j = 0
k = 0
while True:
if k < (5 - i):
print(" ", end='')
else:
break
k += 1
while True:
if j < (2 * i - 1):
print("*", end='')
else:
break
j += 1
print()
i += 1
- 后活
level = int(input())
i = 1
while i <= level:
j = 0
k = 0
while True:
if k < (level - i):
print(" ", end='')
else:
break
k += 1
while True:
if j < (2 * i - 1):
print("*", end='')
else:
break
j += 1
print()
i += 1
心得
for循环中变量的值可以依次取出,实现递增的效果;while循环则采用赋值的方式,增加判断条件,知道自增后值不满足判断条件跳出循环,实现与for循环相同的效果