2

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
Bhargav Rao
  • 45,811
  • 27
  • 120
  • 136

2 Answers2

4

You can use the multiplication * operator to create a string by repeating a character. Also, this would be a very straight forward application for a for loop.

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

def triangle(n):
    print('Making a triangle')
    while n > 0:
        print('0' * n)
        n -= 1
Cory Kramer
  • 107,498
  • 14
  • 145
  • 201
-1

Cyber's answer is good, Here are some one liners:

>>> 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
Bhargav Rao
  • 45,811
  • 27
  • 120
  • 136
  • 3
    Unfortunately not very readable. If you want a one-line approach I would have gone for `print('\n'.join(['0'*i for i in range(n, 0, -1)])` which is arguably slightly more readable, but still much worse than the trvial multiline for-loop in Cyber's answer. But one-liners are fun, I give you that :) – Hannes Ovrén Feb 04 '15 at 12:35
  • @HannesOvrén Thanks Sir, But you forgot a bracket there !!! :) Yep, that's why I stated in the fist that his answer is better ;) – Bhargav Rao Feb 04 '15 at 12:39
  • Doh! At least it drives home the point that one-liners, while cute, are not always the most readable ;) – Hannes Ovrén Feb 04 '15 at 12:54
  • @HannesOvrén Yeah ... We can use them for obfuscated code contests – Bhargav Rao Feb 04 '15 at 12:55
  • 1
    ObComment: Using `.join()` on a list comprehension is more efficient than using it on a generator. See [this answer](http://stackoverflow.com/a/9061024/4014959) from Raymond Hettinger for details. – PM 2Ring Feb 04 '15 at 13:10
  • @PM2Ring Thanks ... The alternatives are only for illustration purpose only ;) Just wanted to give a different way of doing it ... – Bhargav Rao Feb 04 '15 at 13:12
  • 1
    Fair enough, Bhargav. I just don't want Python newbies to fall into the trap of using `.join()` on generators, thinking it's better. But I admit it does look less cluttered. :) – PM 2Ring Feb 04 '15 at 13:17