TechAid24

Your Technical Consultant

Master Python Patterns – Create Pyramids and Patterns with Code

Posted on by Anonymous Guest 1 minute read

This article will review different ways to generate pyramids and patterns in Python. Let’s Master Python Patterns – Create Pyramids and Patterns with Code.

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
***********
 *********
  *******
   *****
    ***
     *

Tags:

Anonymous Guest

An anonymous author is a writer who conceals their true identity when publishing content, often for privacy, security, or confidentiality reasons. This approach is often used in technical articles to focus on the information being presented rather than the author's personal identity.

Leave a Reply

Your email address will not be published. Required fields are marked *