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@H_404_0@方法二:
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,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)@H_404_0@打印结果: @H_404_0@
@H_404_0@2.打印空心菱形 @H_404_0@代码:
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+"*")@H_404_0@打印结果: @H_404_0@
@H_404_0@以上这篇Python实现打印实心和空心菱形就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们。 原文链接:https://www.f2er.com/python/526744.html