Character Classification (Digit / Alpha / Special) in Python
Is @ a letter, digit, or something else? Classify one Python character, validate its length, and learn the Unicode limits of this beginner branching exercise.
1# Program to classify a character as digit, alphabet, or special character23ch = input("Enter a single character: ")45if len(ch) != 1:6 print("Please enter exactly one character.")7else:8 if ch.isdigit():9 print(ch, "is a digit")10 elif ch.isalpha():11 print(ch, "is an alphabet")12 else:13 print(ch, "is a special character")
Output
@ is a special character
@ has length one and fails both classification methods.
In this one
- Validate a one-character response
- Use isdigit and isalpha
- Separate character classification from numeric parsing
How it works
- 1
Read ch and reject len(ch) != 1.
- 2
Test digit membership, then alphabetic membership.
- 3
Print the special-character label if both tests fail.
Edge cases
Space
Enter one space.
Its length is one but both tests fail, so it is special here.
Empty input
Press Enter immediately.
The length guard prints the one-character message.
What's going on
isdigit, isalpha, else. That last category catches punctuation, spaces, and many symbols. It is a leftover bucket defined by this program, not an official Unicode category.
The length check runs before classification because input can return an empty string or a full word. After it passes, isdigit is tested first, then isalpha. @ fails both tests and reaches the special-character message.
These methods recognize more than ASCII. Some characters such as superscript ² satisfy isdigit but are not accepted by int as ordinary decimal input. Classification and number parsing are different jobs. A space is special here; add an isspace branch if your requirements need a separate whitespace category.
After this program
If the idea is still fuzzy, read Day 8: Conditional Statements in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 20 conditional programs, or see every topic on Python exercises.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Where does @ go?
Pick an answer to check it.
Question 2
Can every isdigit character be parsed by int?
Pick an answer to check it.
Questions people ask
Where does @ go?
It goes to else because it is neither a digit nor an alphabetic character.
Can every isdigit character be parsed by int?
No. isdigit includes some Unicode characters that int does not parse as decimal digits.
Why is whitespace not its own category?
The code has no isspace branch, so whitespace remains in the final category.