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

Question:

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:

         * 
        * * 
       * * * 
      * * * * 
     * * * * * 
Asked By: dom598

||

Answers:

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()
Answered By: Eli

Actually, that can be done in a single loop:

for i in range(1, 6):
  print (' ' * (5 - i), '* ' * i)
Answered By: Ayxan Haqverdili

Here is another way

size = 7
m = (2 * size) - 2
for i in range(0, size):
    for j in range(0, m):
        print(end=" ")
    m = m - 1 # decrementing m after each loop
    for j in range(0, i + 1):
        # printing full Triangle pyramid using stars
        print("* ", end=' ')
    print(" ")
Answered By: Imtango30

Try this:

def triangle(n): 
  k = 2*n - 2
  for i in range(0, n):  
   
    for j in range(0, k): 
        print(end=" ") 
  
    k = k - 1
    
    for j in range(0, i+1): 
        print("* ", end="") 
    
    print("r") 
 
n = 5
triangle(n)

Description:

  1. The 1st line defines the function demonstrating how to print the pattern

  2. The 2nd line is for the number of spaces

  3. The 3rd line is for the outer loop to handle number of rows

  4. Inside the outer loop, the 1st inner loop handles the number of spaces and the values change according to requirements

  5. After each iteration of the outer loop, k is decremented

  6. After decrementing the k value, the 2nd inner loop handles the number of columns and the values change according to the outer loop

  7. Print ‘*’ based on j

  8. End the line after each row

Answered By: Pradnya Bolli
function printPyramid($n)
{
    //example 1
    for ($x = 1; $x <= $n; $x++) {
        for ($y = 1; $y <= $x; $y++) {
            echo 'x';
        }
        echo "n";
    }

    // example 2
    for ($x = 1; $x <= $n; $x++) {
        for ($y = $n; $y >= $x; $y--) {
            echo 'x';
        }
        echo "n";
    }

    // example 3

    for($x = 0; $x < $n; $x++) {
        for($y = 0; $y < $n - $x; $y++) {
            echo ' ';
        }
        for($z = 0; $z < $x * 2 +1; $z++) {
            echo 'x';
        }
        echo "n";
    }


}
def triangle(val: str, n: int, type: str):
    for i in range(n):
        if type == "regular":
            print((i + 1) * val)
        elif type == "reversed":
            print((n - i) * val)
        elif type == "inverted":
            print((n - (i + 1)) * " " + (i + 1) * val)
        elif type == "inverted reversed":
            print(i * " " + (val * (n - i)))
        elif type == "triangle":
            print((n - (i + 1)) * " " + ((2*i)+1) * val) 

Call the function like this

triangle("*", 5, 'triangle')

Output

    *
   ***
  *****
 *******
********* 
Answered By: Rishbh Verma

.very simple answer.. don’t go for complex codes..

first try to draw a pyramid. by * ..then u easly understand the code..my solution is.. simplest..here example of 5 lines pyramid..

number_space  =  5
for   i   in   range (5)

     print('/r')

     print (number_space *"  ", end='')

     number_space=number_space-1

     for star in range (i+1):

                print("*",end="  ")
Answered By: jitu

#CPP Program for Print the dynamic pyramid pattern by using one loop in one line.

https://www.linkedin.com/posts/akashdarji8320_cpp-cplusplus-c-activity-6683972516999950336-ttlP

#include

using namespace std;

int main() {
    int rows;

    cout<<"Enter number of rows :: ";
    cin>>rows;

    for( int i = 1, j = rows, k = rows; i <= rows*rows; i++ )
        if( i >= j && cout<<"*" && i % k == 0 && (j += rows-1) && cout<<endl || cout<<" " );
}
Answered By: Akash Darji

This can be achieved in one loop and center padding.

n = int(input('Enter the row you want to print:- '))
sym = input('Enter the symbol you want to print:- ')
for i in range(n):
    print((sym * ((2 * i) + 1)).center((2 * n) - 1, ' '))
Answered By: shubhajit22
# right angle triangle
for i in range(1, 10):
    print("* " * i)

# equilateral triangle
# using reverse of range
for i , j in zip(range(1, 10), reversed(range(1, 10)):
    print(" " * j + "* " * i)

# using only range()
for i, j in zip(range(1, 10), range(10, -1, -1):
    print(" " * j + "* " * i)
Answered By: Megha Krishna

Use String Multiplication,
To simply multiply a string, this is the most straightforward way to go about doing it:

num = 5
for e in range(num, 0, -1):
print(" "(e-1)+(""(num-e+1))+(""*(num-e)))

Answered By: praveen kedar

This can be done in a single loop like the code below:

j=1
for i in range(10,0,-1):
    print(" "*i,"*"*j)
    j+=2
Answered By: Raghul Gopi

Method #1: Comprehension version

This could be easiest way to print any pattern in Python

n = 5
print('n'.join([('* '*i).center(2*n) for i in range(1,n+1)]))

Use center method of str, give it a width as parameter and it will centered the whole string accordingly.

Method #2: Regular version

n = 5
for i in range(1,n+1):
  print(('* '*i).center(2*n))
Answered By: Ali

Here’s the easiest way to print this pattern:

n = int(input("Enter the number of rows: "))
for i in range(1,n+1):
    print(" "*(n-i) + "* "*i)

You have to print spaces (n-i) times, where n is the number of rows and i is for the loop variable, and add it to the stars i times.

Answered By: user16085367
j=1

for i in range(5,0,-1):
    
    print(" "*i, end="")
    
    while j<6:
        print("* "*j)
        j=j+1
        break
Answered By: Abhishek Mathur
#n=Number of rows
def get_triangle(n):
    space,star=" ","* "
    for i in range(1,n+1):
         print((n-i)*space + star*i)

get_triangle(5)

Where n is the number of rows and I is a variable for the loop, you must print spaces (n-i) times and then add it with stars I times. You’ll get the desired pattern as a result. For better comprehension, go to the code stated above.

Answered By: Isuru kavinda
#prints pyramid for given lines 
l = int(input('Enter no of lines'))
for i in range(1,l +1):
    print(' ' * (l-i), ('*') * (i*2-1))
Answered By: vir
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.