python打印等腰三角形与菱形

一.打印下图的等腰三角形

1.首先找出每一行的规律可知 每一行的星号数=行数*2-1，可根据此规律敲出循环语句。
2.代码：

layer = int(input("请输入你要打印的行数："))
for i in range(1,layer+1):
#计算空格的个数
space_num = layer - i
for j in range(0,space_num):
print(" ",end="")
#计算*个数
star_num = 2*i-1
for j in range(0,star_num):
print("*",end="")
print("")



二.打印菱形

2.1 打印下图的菱形

layer = int(input("请输入你要打印的行数："))
for i in range(1,layer//2+2):#前闭后开
#计算空格的个数
space_num = layer - i
for j in range(0,space_num):
print(" ",end="")
#计算*个数
staur_num = 2*i-1
for j in range(0,staur_num):
print("*",end="")
print("")
for i in range(layer//2,0,-1):#前闭后开
#计算空格的个数
space_num = layer - i
for j in range(0,space_num):
print(" ",end="")
#计算*个数
staur_num = 2*i-1
for j in range(0,staur_num):
print("*",end="")
print("")



2.2 打印第二种菱形

layer = int(input("请输入你要打印的行数："))
while layer % 2 == 0:
layer = int(input("对不起，您输入的行数不正确，请输入奇数："))
#上半部分
for i in range(1,layer//2+2): #前闭后开
#计算空格的个数
space_num = layer - i
for j in range(0,space_num):
print(" ",end="")
#计算*个数
star_num = 2*i-1
for j in range(0,star_num):
#判断是不是第一个和最后一个位置
if j == 0 or j == star_num-1:
print("*",end="")
else:
print(" ",end="")
print("")
#下半部分
for i in range(layer//2,0,-1):
#计算空格的个数
space_num = layer - i
for j in range(0,space_num):
print(" ",end="")
#计算*个数
star_num = 2*i-1
for j in range(0,star_num):
#判断是不是第一个和最后一个位置
if j == 0 or j == star_num-1:
print("*",end="")
else:
print(" ",end="")
print("")



2.3 打印第三种菱形

layer = int(input("请输入你要打印的行数："))
while layer % 2 == 0:
layer = int(input("对不起，您输入的行数不正确，请输入奇数："))
for i in range(1,layer//2+2):
space_num = layer - i
for j in range(0,space_num):
print(" ",end="")
star_num = 2*i-1
for j in range(0,star_num):
if j == 0 or j == star_num-1 or i == layer//2+1:
print("*",end="")
else:
print(" ",end="")
print("")
for i in range(layer//2,0,-1):
space_num = layer - i
for j in range(0,space_num):
print(" ",end="")
star_num = 2*i-1
for j in range(0,star_num):
if j == 0 or j == star_num-1:
print("*",end="")
else:
print(" ",end="")
print("")



2.4.打印第四种菱形

layer = int(input("请输入你要打印的行数："))
while layer % 2 == 0:
layer = int(input("对不起，您输入的行数不正确，请输入奇数："))
for i in range(1,layer//2+2):
space_num = layer - i
for j in range(0,space_num):
print(" ",end="")
star_num = 2*i-1
for j in range(0,star_num):
if j == 0 or j == star_num-1 or i == layer//2+1 or j == star_num//2:
print("*",end="")
else:
print(" ",end="")
print("")
for i in range(layer//2,0,-1):
space_num = layer - i
for j in range(0,space_num):
print(" ",end="")
star_num = 2*i-1
for j in range(0,star_num):
if j == 0 or j == star_num-1 or j == star_num//2:
print("*",end="")
else:
print(" ",end="")
print("")


• 9
点赞
• 29
收藏
觉得还不错? 一键收藏
• 0
评论
07-12 867
10-12 1065
04-06 4882
04-18 1952
03-10 4601

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、付费专栏及课程。