Editor

Python Program to Print a Character Pyramid

Beginner · Patterns

A character pyramid is a centred triangle of letters where each row runs from A up to a new letter and back down again: A, then ABA, then ABCBA, and so on. It combines the pyramid layout with `chr()`, which turns a character code into a letter.

Program

character_pyramid.py
rows = 5 # or: rows = int(input("Enter the number of rows: "))
for i in range(1, rows + 1):
print(" " * (rows - i), end="") # centre the row
# Letters going up: A, B, C, ...
for j in range(i):
print(chr(65 + j), end="")
# Letters coming back down, without repeating the middle one
for j in range(i - 2, -1, -1):
print(chr(65 + j), end="")
print() # move to the next line
Output
    A
   ABA
  ABCBA
 ABCDCBA
ABCDEDCBA

How it works

  1. chr(65) is "A", chr(66) is "B", and so on, so chr(65 + j) gives letter number j of the alphabet, counting from 0.
  2. Each row is indented by rows - i spaces so the pyramid is centred, and row i is 2 * i - 1 letters wide.
  3. The first inner loop prints the first i letters, from A up to the middle letter of the row.
  4. The second inner loop counts j down from i - 2 to 0, so it goes back to A without repeating the middle letter.

Other ways to write it

Using string slicing

Using string slicing
import string
rows = 5
letters = string.ascii_uppercase # "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for i in range(1, rows + 1):
left = letters[:i] # for row 3: "ABC"
right = left[:-1][::-1] # for row 3: "BA"
print(" " * (rows - i) + left + right)
Output
    A
   ABA
  ABCBA
 ABCDCBA
ABCDEDCBA

letters[:i] takes the first i letters, and left[:-1][::-1] drops the middle letter and reverses the rest, so no inner loops are needed.

Same letter on each row

Same letter on each row
rows = 5
for i in range(rows):
letter = chr(65 + i)
print(" " * (rows - 1 - i) + (letter + " ") * (i + 1))
Output
    A 
   B B 
  C C C 
 D D D D 
E E E E E

Each row repeats one letter with a space after it, giving A, then B B, then C C C, and the shrinking indent keeps the pyramid centred.

Try it yourself

Change 65 to 97 to build the pyramid from small letters.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises