Python Programs | IT Developer
IT Developer

Python Programs



Share with a Friend

Python Programs - Looping Statements

Print ASCII values of all characters from A to Z - Python Program

Example 1 :

# Program : ASCII values for A-Z for ch in range(ord('A'), ord('Z') + 1): print(f"{chr(ch)} -> {ch}")

Output

 
OUTPUT  :
A -> 65
B -> 66
C -> 67
D -> 68
E -> 69
F -> 70
G -> 71
H -> 72
I -> 73
J -> 74
K -> 75
L -> 76
M -> 77
N -> 78
O -> 79
P -> 80
Q -> 81
R -> 82
S -> 83
T -> 84
U -> 85
V -> 86
W -> 87
X -> 88
Y -> 89
Z -> 90 
 

Explanation

  • Uses ord() to get ASCII value.
  • Uses chr() to convert number back to character.
  • Loops from ASCII 65 to 90.

Example 2 : Advanced Program

# Program : ASCII values for A-Z import string def print_ascii_values_az(): """ Prints the ASCII values of all uppercase characters from A to Z. """ print("Character : ASCII Value") print("---------------------") for char_code in range(ord('A'), ord('Z') + 1): character = chr(char_code) print(f"{character} : {char_code}") if __name__ == "__main__": print_ascii_values_az()

Output

 
OUTPUT  :
Character : ASCII Value
---------------------
A         : 65
B         : 66
C         : 67
D         : 68
E         : 69
F         : 70
G         : 71
H         : 72
I         : 73
J         : 74
K         : 75
L         : 76
M         : 77
N         : 78
O         : 79
P         : 80
Q         : 81
R         : 82
S         : 83
T         : 84
U         : 85
V         : 86
W         : 87
X         : 88
Y         : 89
Z         : 90 
 

Explanation

import string:

This line imports the string module, although it's not strictly necessary for this specific approach, as ord() and chr() are built-in functions.

def print_ascii_values_az()::

This defines a function named print_ascii_values_az to encapsulate the logic.

print("Character : ASCII Value") and  print("---------------------"):

These lines print a header to make the output more readable.

for char_code in range(ord('A'), ord('Z') + 1)::

  • ord('A')returns the ASCII value of 'A' (which is 65).
  • ord('Z')returns the ASCII value of 'Z' (which is 90).
  • range(start, end)generates a sequence of numbers from start up to (but not including) end. By adding + 1 to ord('Z'), the loop includes the ASCII value of 'Z'.
  • The loop iterates through each ASCII value from 'A' to 'Z'.

character = chr(char_code):

The chr() function converts an ASCII value back to its corresponding character.

print(f"{character} : {char_code}"):

This line uses an f-string to format and print each character and its corresponding ASCII value.