我希望所有三种形状都在同一条线上......请帮助......!

时间:2010-04-02 04:10:40

标签: python python-3.x nested-loops

#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()

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

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

尽管如果你的问题出在换行符上,那么你总是可以在print语句的末尾用逗号(',')来解决问题,以跳过换行符,例如:

for i in range(5):
    print "Hello, World!",