Python Programs to Create Pyramid and Patterns

1 min read

In this article, we will go over different ways to generate pyramids and patters in Python.

Half pyramid of asterisks

def half_pyramid(rows):
    for i in range(rows):
        print('*' * (i+1))

half_pyramid(6)

Output

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

An alternate way to generate half pyramid using nested loops in Python.

Program

def half_pyramid(rows):
    for i in range(rows):
        for j in range(i+1):
            print("*", end="")
        print("")

half_pyramid(6)

Output

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

Half pyramid of X's

def half_pyramid(rows):
    for i in range(rows):
        print('X' * (i+1))

half_pyramid(6)

Output

X
XX
XXX
XXXX
XXXXX
XXXXXX

Half pyramid of numbers

def half_pyramid(rows):
    for i in range(rows):
       for j in range(i + 1):
          print(j + 1, end="")
       print("")

half_pyramid(5)

Output

1
12
123
1234
12345

Generating a full pyramid of asterisks

def full_pyramid(rows):
    for i in range(rows):
        print(' '*(rows-i-1) + '*'*(2*i+1))

full_pyramid(6)

Output

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

Full pyramid of X's

def full_pyramid(rows):
    for i in range(rows):
        print(' '*(rows-i-1) + 'X'*(2*i+1))

full_pyramid(6)

Output

     X
    XXX
   XXXXX
  XXXXXXX
 XXXXXXXXX
XXXXXXXXXXX

Reversed pyramid

def inverted_pyramid(rows):
    for i in reversed(range(rows)):
        print(' '*(rows-i-1) + '*'*(2*i+1))

inverted_pyramid(6)

Output

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

PROGRAMS

Latest Articles

Latest from djangocentral

Capturing Query Parameters of request.get in Django

In Django, the request object contains a variety of information about the current HTTP request, including the query parameters. Query parameters are a way to pass additional information in the URL and are used to filter or sort data. The request object p…
Read more →

2 min read

Understanding related_name in Django Models

In Django, related_name is an attribute that can be used to specify the name of the reverse relation from the related model back to the model that defines the relation. It is used to specify the name of the attribute that will be used to access the relat…
Read more →

2 min read