Before printing complex alphabet designs, we must understand how Python represents and manipulates individual characters under the hood.
In computer systems, every character is represented by a unique integer. The most common standard is ASCII (American Standard Code for Information Interchange).
In Python, we have two built-in functions to convert between characters and their integer values:
ord(char): Returns the integer value (ASCII) of a given character.chr(int): Returns the character string of a given integer value (ASCII).
Here are the key ranges you will use when writing character-based loops:
| Character Range | ASCII Range | Description / Examples |
|---|---|---|
'A' to 'Z' |
65 to 90 |
Uppercase English alphabets ('A'=65, 'B'=66, ..., 'Z'=90) |
'a' to 'z' |
97 to 122 |
Lowercase English alphabets ('a'=97, 'b'=98, ..., 'z'=122) |
'0' to '9' |
48 to 57 |
Numeric character characters ('0'=48, '1'=49, ..., '9'=57) |
Input:
# ord() converts character -> integer
print("ASCII value of 'A' is:", ord('A'))
print("ASCII value of 'B' is:", ord('B'))
print("ASCII value of 'a' is:", ord('a'))
# chr() converts integer -> character
print("Character for ASCII 65 is:", chr(65))
print("Character for ASCII 90 is:", chr(90))
print("Character for ASCII 97 is:", chr(97))Output:
ASCII value of 'A' is: 65
ASCII value of 'B' is: 66
ASCII value of 'a' is: 97
Character for ASCII 65 is: A
Character for ASCII 90 is: Z
Character for ASCII 97 is: a
Using chr() and loops, we can print alphabet patterns similarly to number patterns.
Each row prints the same character. Row i (0 to 4) uses ASCII 65 + i (representing 'A', 'B', 'C', etc.).
Input:
n = 5
for i in range(n):
letter = chr(65 + i)
for j in range(i + 1):
print(letter, end=" ")
print()Output:
A
B B
C C C
D D D D
E E E E E
Each row starts at 'A' (ASCII 65) and increments the character by 1 per column.
Input:
n = 5
for i in range(n):
for j in range(i + 1):
letter = chr(65 + j)
print(letter, end=" ")
print()Output:
A
A B
A B C
A B C D
A B C D E
Like Floyd's Triangle, we start a counter at ASCII 65 and increment it for each character printed.
Input:
n = 4
ascii_val = 65
for i in range(n):
for j in range(i + 1):
print(chr(ascii_val), end=" ")
ascii_val += 1
print()Output:
A
B C
D E F
G H I J