Iterate Over Alphabets Using Range
Introduction:
- To iterate over the alphabets using
range()in Python, we use Unicode values of characters to define the range. This allows us to loop through each letter of the alphabet.
Steps:
- Create a Range Object:
- For lowercase alphabets, set
startto the Unicode value of 'a' andstopto the Unicode value of 'z' + 1. - For uppercase alphabets, set
startto the Unicode value of 'A' andstopto the Unicode value of 'Z' + 1. - Use the
ord()function to get the Unicode value of a character.
- For lowercase alphabets, set
- Iterate Over the Range:
- Use a
forloop to iterate over the values in the range and convert each Unicode value back to a character using thechr()function.
- Use a
Examples:
- Iterate Over Lowercase Alphabets Using Range:
Python Program:
pythonstart_ch = 'a' end_ch = 'z' start = ord(start_ch) stop = ord(end_ch) + 1 my_range = range(start, stop) for ch in my_range: print(chr(ch))Output:
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
- Iterate Over Uppercase Alphabets Using Range:
Python Program:
pythonstart_ch = 'A' end_ch = 'Z' start = ord(start_ch) stop = ord(end_ch) + 1 my_range = range(start, stop) for ch in my_range: print(chr(ch))Output:
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
Exercises:
- Iterate Over Lowercase Alphabets:
Write a program to iterate over lowercase English alphabets using
range()and print each character.pythonstart_ch = 'a' end_ch = 'z' start = ord(start_ch) stop = ord(end_ch) + 1 for ch in range(start, stop): print(chr(ch))
- Iterate Over Uppercase Alphabets:
Write a program to iterate over uppercase English alphabets using
range()and print each character.pythonstart_ch = 'A' end_ch = 'Z' start = ord(start_ch) stop = ord(end_ch) + 1 for ch in range(start, stop): print(chr(ch))
Summary:
- In this tutorial, we learned how to iterate over the alphabets using a range in Python. This technique is useful for looping through characters by their Unicode values. Practice these examples to get comfortable with iterating over alphabets using
range()in your Python programs!