[英]Nested loop Triangle with python
I need this nested loop to work and its simple 我需要这个嵌套循环才能工作且简单
def triangle():
print("Making a Triangle")
base = 6
while base > 0:
print('0',0,base)
base = base - 1
triangle()
My current output is: 我目前的输出是:
Making a Triangle
0 0 6
0 0 5
0 0 4
0 0 3
0 0 2
0 0 1
I need my output to look like this: 我需要我的输出看起来像这样:
000000
00000
0000
000
00
0
You can use the multiplication *
operator to create a string by repeating a character. 您可以使用multiplication *
运算符通过重复一个字符来创建一个字符串。 Also, this would be a very straight forward application for a for
loop. 此外,这将是for
循环的非常简单的应用程序。
def triangle(n):
print('making a triangle')
for zeroes in range(n):
print('0' * (n-zeroes))
Testing 测试
>>> triangle(6)
making a triangle
000000
00000
0000
000
00
0
Although if you'd like to stick with a while
loop, you could do 虽然如果你想坚持使用while
循环,你可以做到
def triangle(n):
print('Making a triangle')
while n > 0:
print('0' * n)
n -= 1
Cyber's answer is good, Here are some one liners: 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.