Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

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.

IntermediatePhase 1 - Level 4: Logical Operators & Compound StatementsExample 1 of 10
check-letter-digit-or-neither.py
1# Take character
2ch = input("Enter a character: ")
3
4# Check type
5if 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. 1

    Read ch as text.

  2. 2

    Try isalpha before isdigit.

  3. 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.