Skip to content
Advertisement

Python pattern right triangle with while loop in python

I need to print the numbers in a specific shape and order with a while loop, for loop is not allowed, but I don’t understand nor can I find anything on the web that can help me understand how can I move the figure a bit to the right or how I can flip it around. Here is the code I have at the moment. I wanted to use a delta, which is 8 spaces multiplied with the digits behind to move the shape to the right and convert everything behind the top shape into empty spaces but don’t know how to do it

    i = 1
delta = 8
while i <= 5:
    j = 1
    while j <= i:
        print(j, end="")
        j += 1
    print()
    i += 1
a = 5
while a >= 1:
    b = 1
    while b <= a:
        print(b, end="")
        b += 1
    print()
    a -= 1

enter image description here

and here is the result I get,I need to move the first loop to the right so I can get this shape enter image description here

After that I need to make the lower loop inverted and to use the number 1 from the top loop to make it seem like it fits with the lower loop one, I was able to do it with a for loop but i am not sure how I can do it with a while loop and maintain the shape.

Advertisement

Answer

You can definitely use a delta, just print it before each number print loop to get the spacing. For the second loop you can decrement it by 2 each time so the ending stays in the same place as the first loop starts.

i = 1
delta = 8
while i <= 5:
    j = 1
    print(delta*" ",end="")
    while j <= i:
        print(j, end=" ")
        j += 1
    print()
    i += 1
i = 2
while i <= 5:
    j = 1
    delta -= 2
    print(delta*" ",end="")
    while j <= i:
        print(j, end=" ")
        j += 1
    print()
    i += 1

Edit: This is looking suspiciously like a question from a class so I tried to keep the code in what appears to be your style lol

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement