user3554208
user3554208

Reputation: 21

Python nested loop triangle

The output I am trying to achieve is :

##
# #
#  #
#   #
#    #
#     #

The code I have is :

NUM_STEPS = 6

for r in range(NUM_STEPS):
   for c in range(r):
      print(' ', end='')
   print('#','\t')
   print('#')   

Its close, but not quite the output I am trying to achieve. Any help or suggestions are most appreciated.

Upvotes: 2

Views: 216

Answers (2)

rongenre
rongenre

Reputation: 1334

The main thing is you should use '+' (or concat) to build up a string before printing it. You can eliminate the inner loop by using '*' to make r spaces, which cleans things up a lot.

NUM_STEPS = 6
for r in range(NUM_STEPS):
    print("#" + (' ' * r) + "#")

Upvotes: 4

laurencevs
laurencevs

Reputation: 923

This seemed to work when I tried it:

for r in range(NUM_STEPS):
    print("#", end = "")
    for c in range(r):
        print(" ", end = "")
    print("#")

I hope it helps.

Upvotes: 1

Related Questions