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:

  1. Create a Range Object:
    • For lowercase alphabets, set start to the Unicode value of 'a' and stop to the Unicode value of 'z' + 1.
    • For uppercase alphabets, set start to the Unicode value of 'A' and stop to the Unicode value of 'Z' + 1.
    • Use the ord() function to get the Unicode value of a character.
  2. Iterate Over the Range:
    • Use a for loop to iterate over the values in the range and convert each Unicode value back to a character using the chr() function.

Examples:

  1. Iterate Over Lowercase Alphabets Using Range:
    • Python Program:

      python
      start_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
      
  2. Iterate Over Uppercase Alphabets Using Range:
    • Python Program:

      python
      start_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:

  1. Iterate Over Lowercase Alphabets:
    • Write a program to iterate over lowercase English alphabets using range() and print each character.

      python
      start_ch = 'a'
      end_ch = 'z'
      
      start = ord(start_ch)
      stop = ord(end_ch) + 1
      for ch in range(start, stop):
          print(chr(ch))
      
  2. Iterate Over Uppercase Alphabets:
    • Write a program to iterate over uppercase English alphabets using range() and print each character.

      python
      start_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!