Find ASCII Value of a Character in Python
What number represents A? Use Python ord to inspect a character, reject empty or longer responses, and understand the Unicode detail behind this ASCII exercise.
1# Program to find the ASCII value of a character23ch = input("Enter a character: ")45if len(ch) != 1:6 print("Please enter exactly one character.")7else:8 print("The ASCII value of", ch, "is", ord(ch))
Sample Output
The ASCII value of A is 65
Uppercase A has code point 65; lowercase a would give 97.
In this one
- Use ord on one character
- Validate string length before conversion
- Distinguish Unicode from ASCII
How it works
- 1
Read the response into ch without numeric conversion.
- 2
Print the validation message when len(ch) is not 1.
- 3
Otherwise call ord(ch) and display its code point.
Edge cases
Empty input
Press Enter immediately.
len is zero, so the program prints the validation message without calling ord.
Non-ASCII letter
Enter a single character such as é.
ord returns its Unicode code point, even though the printed label says ASCII.
What's going on
ord('A') is 65. ord('a') is 97. Same function, different code points. A code point is a number assigned to a Unicode character; English ASCII characters keep their familiar values inside Unicode.
input can return an empty string or a whole name. len(ch) != 1 catches both before ord is called. The else branch runs only when there is exactly one code point in the input string.
ord('') and ord('AB') raise TypeError. The check turns those mistakes into a useful message instead. chr(65) goes the other direction and returns 'A'. Some visible symbols use several code points, so what looks like one symbol on screen may still fail this length check.
After this program
If the idea is still fuzzy, read Day 1: Introduction to Python in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 25 basic python programs, or see every topic on Python exercises.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Does ord work only for ASCII?
Pick an answer to check it.
Question 2
Why check len before calling ord?
Pick an answer to check it.
Questions people ask
Does ord work only for ASCII?
No. ord returns Unicode code points; ASCII is a small subset.
Why check len before calling ord?
ord requires exactly one character, so the check prevents TypeError for empty or longer strings.
What reverses ord for a valid code point?
chr converts a numeric code point back to a one-character string.