Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print a Triangle Pyramid pattern using a for loop in Python?

I am using the following for loop code to print a star pattern and the code is working perfectly fine.

Here is my code:

for i in range(1,6):
    for j in range(i):
        print("*", end=" ")
    print()

This code displays:

* 
* * 
* * * 
* * * * 
* * * * * 

Now, my question is how to print the output like this:

         * 
        * * 
       * * * 
      * * * * 
     * * * * * 
like image 818
dom598 Avatar asked Jun 07 '26 12:06

dom598


2 Answers

Actually, that can be done in a single loop:

for i in range(1, 6):
  print (' ' * (5 - i), '* ' * i)
like image 148
Ayxan Haqverdili Avatar answered Jun 10 '26 04:06

Ayxan Haqverdili


You just need to add spaces before the *:

for i in range(1,6):
    for j in range(6-i):
        print(" ", end="")
    for j in range(i):
        print("*", end=" ")
    print()
like image 27
Eli Avatar answered Jun 10 '26 02:06

Eli



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!