Character Classification (Digit / Alpha / Special) in Python

isdigit, isalpha, else special. Space counts as special. That bothers people.

BeginnerConditional ProgramsExample 3 of 20
character-classification-digit-alpha-special.py
1# Program to classify a character as digit, alphabet, or special character
2
3ch = input("Enter a single character: ")
4
5if 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

Enter a single character: @
@ is a special character

In this one

  • isdigit / isalpha / else
  • space falls in the else. that's a choice

What's going on

isdigit() / isalpha() / else. The else is punctuation, space, emoji, whatever.

Space is "special" here. If that feels wrong, add isspace(). I didn't, on purpose — one extra branch and this stops being a 10-line example.

len != 1 again. input() plus enter can be empty.

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.