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
author's image
Abhijeet Pal Author and Editor in Chief @djangocentral

Abhijeet is a full-stack software developer from India with a strong focus on backend and system design. He is driven by the need to create impactful solutions that add value to the internet in any way possible.

LinkedIn Twitter Github

Latest Articles

Latest from djangocentral

Django 4.1 adds async-compatible interface to QuerySet

The much-awaited pull request for an async-compatible interface to Queryset just got merged into the main branch of Django.Pull Request - https://github.com/django/django/pull/14843 The Django core team has been progressively adding async suppor…
Read more →

3 min read

Making Django Admin Jazzy With django-jazzmin

Django admin is undoubtedly one of the most useful apps of Django. Over the years there has been very little change in the admin app as far as the UX is concerned and it's not a bad thing at all. Django admin was designed to provide a simple and minimali…
Read more →

4 min read