How to Create a Loop from A to Z in Python?

Estimated read time 2 min read

To create a loop that iterates over the alphabet from A to Z in Python, you can use the string module and the for loop.

Here’s an example of creating a loop that iterates over the alphabet from A to Z:

import string

for letter in string.ascii_uppercase:
    print(letter)

In this example, we use the string.ascii_uppercase constant from the string module, which is a string of all uppercase letters in the English alphabet. We iterate over each letter in the string using a for loop and print the letter.

The output of this code is:

A
B
C
D
E
F
G
H
I
J
K
L
M
N
O
P
Q
R
S
T
U
V
W
X
Y
Z

Note that you can also use the range() function and the chr() function to generate a sequence of letters based on their ASCII codes. Here’s an example:

for i in range(65, 91):
    letter = chr(i)
    print(letter)

In this example, we use the range() function to generate a sequence of integers from 65 (the ASCII code for 'A') to 91 (the ASCII code for 'Z'). We use the chr() function to convert each integer to its corresponding ASCII character, which is a letter in the English alphabet. We then print each letter using a for loop.

The output of this code is the same as before:

A
B
C
D
E
F
G
H
I
J
K
L
M
N
O
P
Q
R
S
T
U
V
W
X
Y
Z

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply