Check Letter, Digit, or Neither
Classify entered text as letters, digits, or neither with Python. Students compare string tests and discover why a character prompt does not enforce length.
1# Take character2ch = input("Enter a character: ")34# Check type5if ch.isalpha():6 print("Letter")7elif ch.isdigit():8 print("Digit")9else:10 print("Neither")
Output
Enter a character: a Letter Enter a character: 5 Digit Enter a character: @ Neither
In this one
- Use alphabetic and digit tests
- Classify nonmatching input
- Recognize multi-character responses
How it works
- 1
Read ch as text.
- 2
Try isalpha before isdigit.
- 3
Print the matching class or Neither.
Edge cases
What does a1 produce?
What does a1 produce?
Neither, because it mixes letters and digits.
What does an empty response produce?
What does an empty response produce?
Neither; both string tests require nonempty text.
What's going on
isalpha asks whether a nonempty response consists entirely of letters. If it fails, isdigit asks whether the response consists entirely of digit characters.
Only the first successful branch prints. The sample a is a Letter and 5 is a Digit. The methods also accept longer responses such as abc or 123, so a separate length check is needed for exactly one character.
What does a1 produce? Neither, because it mixes letters and digits.
What does an empty response produce? Neither; both string tests require nonempty text.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Which response satisfies isalpha?
Pick an answer to check it.
Question 2
What does a1 produce?
Pick an answer to check it.
Questions people ask
What does a1 produce?
Neither, because it mixes letters and digits.
What does an empty response produce?
Neither; both string tests require nonempty text.
Which response satisfies isalpha?
abc.
๐Related Content
- ๐
Phase 1 - Learn Concepts
Review Phase 1 concepts and explanations
- ๐
Phase 1 - Quiz
Test your Phase 1 understanding with quiz questions
- ๐ป
Phase 1 - All Practice Problems
Explore all practice problems for Phase 1
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum