Python Program to Print Alphabet Pattern
for loops and the chr() function, for example: for i in range(5): print(' '.join(chr(65 + j) for j in range(i + 1))).Examples
How to Think About It
chr() function helps convert numbers to letters.Algorithm
Code
n = 5 for i in range(n): for j in range(i + 1): print(chr(65 + j), end=' ') print()
Dry Run
Let's trace the example where n=3 through the code.
Start outer loop with i=0
Print letters from j=0 to 0: chr(65+0) = 'A'
Outer loop i=1
Print letters j=0 to 1: 'A' and 'B'
Outer loop i=2
Print letters j=0 to 2: 'A', 'B', 'C'
| i | Printed Letters |
|---|---|
| 0 | A |
| 1 | A B |
| 2 | A B C |
Why This Works
Step 1: Outer loop controls rows
The outer for loop runs from 0 to n-1, controlling how many rows to print.
Step 2: Inner loop prints letters
The inner for loop prints letters from 'A' up to the current row's letter using chr(65 + j).
Step 3: Print new line after each row
After printing letters in a row, print() moves to the next line for the next row.
Alternative Approaches
n = 5 for i in range(n): print(' '.join(chr(65 + j) for j in range(i + 1)))
n = 5 i = 0 while i < n: j = 0 while j <= i: print(chr(65 + j), end=' ') j += 1 print() i += 1
Complexity: O(n^2) time, O(1) space
Time Complexity
The program uses nested loops where the outer loop runs n times and the inner loop runs up to n times, resulting in O(n^2) time.
Space Complexity
The program uses constant extra space, only variables for loop counters, so O(1) space.
Which Approach is Fastest?
Both for-loop and while-loop approaches have similar time complexity; using string join is cleaner but performance difference is negligible.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Nested for loops | O(n^2) | O(1) | Simple and clear for beginners |
| String join with comprehension | O(n^2) | O(1) | Concise and readable code |
| While loops | O(n^2) | O(1) | Beginners preferring while loops |
chr(65 + index) to convert numbers to uppercase letters starting from 'A'.