我正在练习打印各种类型的图案,我被困在六角形图案中。我正在使用Asterisk(*)打印它。
它应该是动态的。我几乎完成了它,但最后一部分。我已经将所有部分分成块并使用while循环和if条件执行所有块。
sideLength = 5
totalLength = (sideLength)*2 + (sideLength-2)
loop =1
while loop<=totalLength :
if (loop==1) or (loop==totalLength):
print " "*((totalLength - sideLength)//2) + "*"* sideLength + " "*((totalLength- sideLength)//2)
if loop>(sideLength-1) and loop<= (sideLength-1)+sideLength:
print "*" + " "*(totalLength-2) + "*"
if (loop>=1) and (loop)<(sideLength-1):
print " "*(sideLength- 1- loop) + "*" + " " * ((sideLength-2) + 2*(loop)) + "*" + " "*(sideLength- 1- loop)
if loop>((totalLength//2) + (sideLength//2)) and loop<(totalLength-1):
print " "*(loop - 1 - sideLength ) + "*"
loop+=1
从最后一个if条件出现问题。
答案 0 :(得分:0)
要处理任意长度&gt; 1,您必须更改第二个if语句。我为你修好了最后一个:
sideLength = 5
totalLength = (sideLength) + 2*(sideLength-1)
loop = 1
while loop<=totalLength :
if loop==1 or loop==totalLength:
print " "*(sideLength-1) + "*"* sideLength + " "*(sideLength-1)
if loop>sideLength-1 and loop<= 2*sideLength-1:
print "*" + " "*(totalLength-2) + "*"
if loop>=1 and loop<sideLength-1:
print " "*(sideLength- 1- loop) + "*" + " " * ((sideLength-2) + 2*(loop)) + "*" + " "*(sideLength- 1- loop)
if loop>=2*sideLength-1 and loop<totalLength-1:
print " "*(loop-totalLength+sideLength) + "*"+ " " *(totalLength-2*(loop-totalLength+sideLength+1)) + "*" + " "*(sideLength- 1- loop)
loop+=1