我需要这个嵌套循环才能工作并且简单
def triangle():
print("Making a Triangle")
base = 6
while base > 0:
print('0',0,base)
base = base - 1
triangle()
我目前的输出是:
Making a Triangle
0 0 6
0 0 5
0 0 4
0 0 3
0 0 2
0 0 1
我需要输出看起来像这样:
000000
00000
0000
000
00
0
答案 0 :(得分:3)
您可以使用乘法*
运算符通过重复一个字符来创建字符串。此外,这将是for
循环的非常直接的应用程序。
def triangle(n):
print('making a triangle')
for zeroes in range(n):
print('0' * (n-zeroes))
测试
>>> triangle(6)
making a triangle
000000
00000
0000
000
00
0
虽然如果你想坚持while
循环,你可以做
def triangle(n):
print('Making a triangle')
while n > 0:
print('0' * n)
n -= 1
答案 1 :(得分:0)
Cyber的回答很好,以下是一些内容:
>>> for i in ['0'*j for j in range(n,0,-1)]: print (i) # Old-Style
...
000000
00000
0000
000
00
0
>>> print('\n'.join(['0'*i for i in range(n, 0, -1)])) # Thanks to Hannes Ovren
000000
00000
0000
000
00
0
>>> print('\n'.join('0'*i for i in range(n, 0, -1))) # Using a generator expression
000000
00000
0000
000
00
0
>>> print '\n'.join([('0'*6)[:n-i] for i in range(n)]) # Little complicated
000000
00000
0000
000
00
0