How to Create a Pyramidal Print in Python?

Estimated read time 2 min read

To create a pyramidal print in Python, you can use nested loops to print out the desired pattern of stars or other characters. Here’s an example of how you can create a pyramidal print in Python:

# Define the height of the pyramid
height = 5

# Loop through each row of the pyramid
for i in range(height):
    # Print the leading spaces
    for j in range(height - i - 1):
        print(" ", end="")
    # Print the stars for this row
    for j in range(2 * i + 1):
        print("*", end="")
    # Move to the next line
    print()

In this example, we define the height of the pyramid to be 5. We then use two nested loops to print out each row of the pyramid. The first loop (with index i) controls the row number, and the second loop (with index j) controls the number of stars to print for that row.

For each row, we print a certain number of leading spaces (equal to the height minus the row number minus one) to center the stars. We then print a certain number of stars (equal to 2 times the row number plus one) to create the pyramid shape. Finally, we move to the next line to start the next row.

When you run this code, you should see the following output:

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

This is a pyramidal print made up of stars. You can modify the code to print out other characters or use a different height for the pyramid as needed.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply