0

I am using nested loops to create a reverse triangle that goes down by whatever character amount I enter. For example, if 8 is entered, my triangle is supposed to look like this

xxxxxxxx
 xxxxxxx
  xxxxxx
   xxxxx
    xxxx
     xxx
      xx
       x

My code currently consists of whats below, but the output is not what I was looking for.

row = 1
while row <= size:
    # Output a single row
    col = size - row + 1
    while col <= size:
        # Output the drawing character
        print(end=' ')

        # The next column number
        col = col + 1
    col = 0
    while col <= size - row:
        print(drawingChar, end=' ')
        col = col + 1
    row = row + 1
    print()   
print()

Output:

 x x x x x x x x 
  x x x x x x x 
   x x x x x x 
    x x x x x 
     x x x x 
      x x x 
       x x 
        x 

Im sure i screwed up something minor with my <= size or col somewhere. All input is appreciated.

6
  • possible duplicate of reverse upside down asterisk triangle in python Commented Apr 3, 2017 at 21:44
  • @downshift i saw that post, and took some things from that answer, but im still getting that down pointing equilateral triangle Commented Apr 3, 2017 at 21:45
  • ok sorry that one wasn't helpful. Try removing the <space> character from the end parameter in the second while loop: print(drawingChar, end='') Commented Apr 3, 2017 at 21:51
  • 1
    Yes, @Astonishing, it's just that one space character in end=' ') that you should remove, that's all Commented Apr 3, 2017 at 21:53
  • 1
    @downshift That was it, thanks Commented Apr 3, 2017 at 21:57

1 Answer 1

1
>>> def foo(n):
...    for i in range(n):
...       print((" "*i) + ("x"*(n-i)))
... 
>>> foo(8)
xxxxxxxx
 xxxxxxx
  xxxxxx
   xxxxx
    xxxx
     xxx
      xx
       x

Edit:

Since OP is asking for nested loop solution, here it is:

>>> def foo(n):
...    out = ""
...    for i in range(n):
...       for _ in range(i):
...          out += " "
...       for _ in range(n-i):
...          out += "x"
...       out += "\n"
...    print(out)
... 
>>> foo(8)
xxxxxxxx
 xxxxxxx
  xxxxxx
   xxxxx
    xxxx
     xxx
      xx
       x
Sign up to request clarification or add additional context in comments.

4 Comments

I need to do it the way I am doing it with nested loops
@Astonishing then convert my solution to use nested loops, however, there is no point to do that in general.
I am in an intro python class and have to use nested loops and I have absolutely no idea what any of what you gave me means. I think the code i provided is very close to what im trying to accomplish
@Astonishing I added nested loops solution to my answer, check it out

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.