在Python中打印箭头图案的反转

时间:2016-02-29 13:10:48

标签: python for-loop

现在这段代码给了我:

*
 *
  *
   *

我似乎无法弄清楚如何完成箭头(换句话说,颠倒第一张照片):

*
 *
  *
   *
   *
  *
 *
*

-

columns = int(input("How many columns? "))

while columns <= 0:
    print ("Invalid entry, try again!")
    columns = int(input("How many columns? "))

x = 1
for x in range(columns):
        for x in range(x):print(" ", end="")
        print("*")

4 个答案:

答案 0 :(得分:2)

我会这样做:

1 - 我使用*中的chain来构建值列表,以调整printitertools的位置 2 - 在遍历列表时,我将调整值传递给str.rjust

>>> from itertools import chain
>>> col = int(input('Enter nb of columns:'))
Enter nb of columns:7
>>> l = chain(range(1,col), range(col,0,-1))
>>> 
>>> for x in l:
    print('*'.rjust(x))


*
 *
  *
   *
    *
     *
      *
     *
    *
   *
  *
 *
*

答案 1 :(得分:0)

您可以在第一个循环结束后向后运行循环。 range()可以采用三个参数。开始,停止,步骤。使用步骤,您可以向后移动。

for x in range(1, columns):
    for x in range(x):
        print(" ", end="")
    print("*")

for x in range(columns,0,-1): 
    for x in range(x):
        print(" ", end="")
    print("*")

答案 2 :(得分:0)

对于第一部分(上半部分),只需添加空格作为索引,后半部分添加空格并减少每次迭代:

 for x in range(columns):
        if(x<(columns//2)):print (" "*x+"*")
        else : print(" "*(-x+(columns-1))+"*")

 columns = 8  

*
 *
  *
   *
   *
  *
 *
*

columns = 7   

*
 *
  *
   *
  *
 *
*

答案 3 :(得分:0)

v = [" ", " ", " ", " ", " ", " ", " "]

col = int(input('Enter nb of columns:'))
for x in range(1, col):
    for i in range(0,x):
        v[x] = "*"
    print x * " " ,v[x]
x = col
for x in range(x, 0, -1):
    for i in range(x,0,-1):
        v[x] = "*"
    print x * " " ,v[x]