Python Program for Letter Pyramid Pattern

1. Introduction

The letter pyramid pattern is a creative exercise that combines programming logic with a bit of character manipulation to create a visually appealing pattern. In this Python tutorial, we'll create a program that prints a pyramid pattern using letters from the alphabet. This is an excellent way to learn about loops, nested loops, and working with characters in Python.

2. Program Steps

1. Ask the user to enter a single uppercase letter, which will determine the height of the pyramid and the range of letters to print.

2. Calculate the height of the pyramid based on the input letter's position in the alphabet.

3. Use nested loops to print each row of the pyramid, adjusting the number of spaces and letters printed on each line.

3. Code Program

# User input for the letter
letter = input("Enter an uppercase letter: ")
height = ord(letter) - ord('A') + 1

# Outer loop for each row of the pyramid
for i in range(1, height + 1):
    # Print leading spaces
    print(' ' * (height - i), end='')

    # Print letters in ascending order
    for j in range(1, i + 1):
        print(chr(ord('A') + j - 1), end='')

    # Print letters in descending order
    for j in range(i - 1, 0, -1):
        print(chr(ord('A') + j - 1), end='')

    # Move to the next line
    print()

Output:

Enter an uppercase letter: F
     A
    ABA
   ABCBA
  ABCDCBA
 ABCDEDCBA
ABCDEFEDCBA

Explanation:

1. The program starts by asking the user to enter an uppercase letter. This letter determines both the height of the pyramid and how far into the alphabet the pattern will go.

2. The height of the pyramid is calculated by finding the difference between the ASCII values of the input letter and 'A', then adding 1. This determines how many rows the pyramid will have.

3. The outer loop iterates once for each row of the pyramid. Within this loop:

- Leading spaces are printed to center the pyramid horizontally. The number of spaces decreases with each row down the pyramid.

- The next loop prints letters in ascending alphabetical order from 'A' up to the current row's letter.

- Following that, another loop prints letters in descending order to complete the other half of the pyramid.

4. The use of end='' in the print statements ensures that the characters are printed on the same line, with a call to print() without arguments used to move to the next line after each row is complete.

5. This pattern of incrementing and then decrementing the printed letters, combined with decreasing spaces, creates a symmetric letter pyramid that showcases the beauty of programming logic with a simple application.


Comments