script_22.py - Character Type Detector
Code
#!/usr/bin/env python3
"""Character type detector"""
char = input("Enter a character: ")
if len(char) == 1:
if char.isdigit():
print(f"{char} is a digit")
elif char.isalpha():
print(f"{char} is a letter")
elif char.isspace():
print("This is a whitespace character")
else:
print(f"{char} is a special character")
else:
print("Please enter only one character")
Explanation
Line 4: char = input("Enter a character: ")
- char is string type
- Can contain any characters
Line 6: if len(char) == 1:
- len() returns integer (string length)
- Validates user entered exactly one character
- Outer guard clause
Line 7: if char.isdigit():
- .isdigit() is string method returning boolean
- Returns True if string contains only digit characters (0-9)
- For single character: checks if it's 0, 1, 2, 3, 4, 5, 6, 7, 8, or 9
- Nested if (inside the length validation)
Line 9: elif char.isalpha():
- .isalpha() is string method returning boolean
- Returns True if string contains only alphabetic characters (a-z, A-Z)
- Checks both uppercase and lowercase letters
- False for digits, symbols, spaces
Line 11: elif char.isspace():
- .isspace() is string method returning boolean
- Returns True for whitespace characters: space, tab, newline
- Examples: " ", "\t", "\n"
- Returns False for all other characters
Line 13: else: (inner)
- Executes when character is not digit, not letter, not whitespace
- Must be special character/symbol
- Examples: !, @, #, $, %, &, *, (, ), etc.
Line 15: else: (outer)
- Handles when user entered zero characters or multiple characters
- Guard against invalid input length