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
A ABA ABCBA ABCDCBA ABCDEDCBA
How it works
chr(65)is "A",chr(66)is "B", and so on, sochr(65 + j)gives letter numberjof the alphabet, counting from 0.- Each row is indented by
rows - ispaces so the pyramid is centred, and rowiis2 * i - 1letters wide. - The first inner loop prints the first
iletters, from A up to the middle letter of the row. - The second inner loop counts
jdown fromi - 2to 0, so it goes back to A without repeating the middle letter.
Other ways to write it
Using string slicing
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
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.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises