2
#Top half of triangle    
for rows in range (5):
     for row in range (12):
          print("-", end='')
     print()


for row in range (5):
     stars=0
     while stars<=row:
          print("*", end='')
          stars=stars+1
     print()


for row in range(5):
     star=4
     while star>=row:
          print("*", end='')
          star=star-1
     print()
4

2 回答 2

3
shape1 = [12*'-' for i in range(5)]                  # segments of rectangle
shape2 = [i*'*' + (5-i)*' ' for i in range(1,5+1)]   # segments of 1st triangle
shape3 = [(5-i)*' ' + i*'*' for i in range(1,5+1)]   # segments of 2nd triangle 

for line in zip(shape1, shape2, shape3):
    print("   ".join(line))

编辑:根据要求提供详细版本(但我这里没有 python 3;以下代码在 python 2.x 中有效,因此您必须稍微修改打印指令):

for line in range(1, 5+1):        # for each line
     for c in range (12):         # print a bit of the first shape
          print '-',
     print "   ", 

     for c in range (line)    :   # a bit of the second
          print '*',
     for c in range (5-line):
          print ' ',
     print "   ",

     for c in range (5+1-line):   # and a bit of the third
          print '*',
     #for c in range (line):
     #     print ' ',
     print
于 2010-04-02T04:26:35.753 回答
0

首先,您的第一个 print 语句在语法上是错误的:print("-", end='')会抛出一个语法错误,询问 end='' 是什么。

不过,如果您的问题与换行符有关,那么您始终可以在 print 语句的末尾使用逗号 (',') 来跳过换行符,例如:

for i in range(5):
    print "Hello, World!",
于 2010-04-02T04:28:56.973 回答