好的,首先要做的是:你在第一行中的定义是正确的:
count=10
star="*"
for i in range(count):
如果你仔细观察这个图案,你就会注意到,如果你仔细观察这个图案,每一条线都是由奇数颗星星组成的:1,3,5……所以从根本上说,你想跳过每一次有偶数颗星的迭代,这就是continue
的意义所在,把你带到下一个迭代循环.
但是请记住,Pythonrange
迭代从0开始,所以每一行都比它的索引多包含一个星号.总而言之,you want to print even lines (with an odd number of stars) and skip odd lines (with an even number of stars)项:
if (i%2 == 1): # if you're looking at an odd line (with an even number of stars)
continue # skip this iteration
else: # we're now sure we're on an even line
现在我们只有偶数线了.对于这些行中的每一行,我们希望保留与行索引(i
索引)+1一样多的星号.当使用print
方法时,end
的缺省值是\n
,这是换行符,所以当您使用print
时,默认情况下它打印一行并转到下一行.print(star, end="")
指令将通过强制代码保持在同一行而不是转到新行来帮助我们.还记得我们说过我们想打印(i+1)颗星星吗?
for x in range(i):
print(star,end="") #print our star and prevents the new line
print(star) #once we printed our i stars, we print the i+1 and go to a new line
总而言之:
count=10
star="*"
for i in range (count):
if (i%2 == 1): # if you're looking at an odd line (with an even number of stars)
continue # skip this iteration
else: # we're now sure we're on an even line
for x in range(i):
print(star,end="") #print our star and stay on the same line
print(star) #once we printed our i stars, we print the i+1 and go to a new line