打印菱形
方法一:
layer = int(input("请输入你要打印的层数(奇数):"))
#条件判断:打印的层数必须为奇数
while layer%2 == 0:
layer = int(input("输入错误,请再次输入:"))
#上半部分
for i in range(1,layer//2+2):
print(" "*(layer-i),end="")
for j in range(1,2*i):
print("*",end="")
print()
#下半部分
for i in range(layer//2,0,-1):
print(" "*(layer-i),end="")
for j in range(1,2*i):
print("*",end="")
print()
效果:
方法二:
a = int(input("请输入菱形的层数:"))
n = (a+1)/2
n = int(n)
for i in range(-n+1,n):
if i<0:
j=-i
else:
j=i
print(" "*j+"*"*(2*n-1-2*j))
打印空心菱形需要加上if else 语句 其他代码和打印菱形相同
layer = int(input("请输入你要打印的层数(奇数):"))
#条件判断:打印的层数必须为奇数
while layer%2 == 0:
layer = int(input("输入错误,请再次输入:"))
#打印图形的上半部分
for i in range(1,layer//2+2):
print(" "*(layer-i),end="")
for j in range(1,2*i):
if j == 1 or j == 2*i - 1 :
print("*",end="")
else:
print(" ",end="")
print()
#下半部分
for i in range(layer//2,0,-1):
print(" "*(layer-i),end="")
for j in range(1,2*i):
if j == 1 or j == 2*i - 1:
print("*",end="")
else:
print(" ",end="")
print()
效果:
打印此图形重点在于打印对角线
需要在if条件原有的基础上加上相应条件
(i == layer//2+1 or j == i )
layer = int(input("请输入你要打印的层数(奇数):"))
#条件判断:打印的层数必须为奇数
while layer%2 == 0:
layer = int(input("输入错误,请再次输入:"))
#打印图形的上半部分
for i in range(1,layer//2+2):
print(" "*(layer-i),end="")
for j in range(1,2*i):
if j == 1 or j == 2*i - 1 or i == layer//2+1 or j == i:
print("*",end="")
else:
print(" ",end="")
print()
#下半部分
for i in range(layer//2,0,-1):
print(" "*(layer-i),end="")
for j in range(1,2*i):
if j == 1 or j == 2*i - 1 or j == i:
print("*",end="")
else:
print(" ",end="")
print()
效果: