方法一:
a = int(input("请输入菱形每条边星星的个数:"))
b = a
c = a
for i in range(1, a + 1): # 先打印正三角,由空格和*根据规律组成
print(" " * (b - 1), "*" * (2 * i - 1))
b -= 1
if i == a: # 临界点,当打印到此,开始打印倒三角
for y in range(1, a):
print(" " * y, "*" * (2*c-3))
c -= 1
方法二:
n = int(input("输入要打印的菱形的每个边的元素个数:"))
list_a = [i for i in range(n)] # 生成前n行的行数列表,例如[0,1,2,3,4]
list_b = list_a[0:len(list_a) - 1:] # 生成剩余行数列表并反转,例如[0,1,2,3]
list_c = list_b[::-1] # 对剩余行数列表并反转便于打印操作
list_d = list_a + list_c # 将两个列表合并
print(list_d)
b = [' ' * (n - i) + '*' * (2 * i + 1) for i in list_d] # 根据规律,打印空格" "和"*"
for line in b:
print(line)
打印结果:
2.打印空心菱形
代码:
a = int(input("请输入菱形每条边星星的个数:"))
b = a
c = a
print(" " * (a - 1), "*")
for i in range(2, a+1): # 先打印正三角,由空格和*根据规律组成
print(" " * (b - 1) + "*" + " " * (2 * i - 3) + "*")
b -= 1
if i == a: # 临界点,当打印到此,开始打印倒三角
for y in range(2, a):
print(" " * y+"*"+" "*(2*c-5)+ "*" )
c -= 1
print(" "*a+"*")
打印结果: