Use str.isdigit() when a program needs to check whether a nonempty string contains only the digits 0–9 before converting it with int(). It returns True or False. section 5.9 section 8.7
Work through these boundaries before choosing it:
- Accepts strings such as "42", but rejects empty strings, floating-point text such as "3.5", and negative text such as "-3". section 5.9 section 8.7
- Filters list-comprehension input before int() runs, preventing conversion errors for entries such as "abcd". section 8.7
- Prefer try/except ValueError when valid integers may include negative values; isdigit checks characters, not general convertibility. section 8.7
- Distinguishes among isdigit, isdecimal, and isnumeric when their similar behavior matters. section 5.9
Validate before conversion
s = input('Enter a number: ').strip()\n\nif s.isdigit():\n n = int(s)\n print(f'You entered {n}. 2*{n} = {2*n}.')\nelse:\n print(f'{s} is not numeric.')
s = input('Enter a number: ').strip()
try:
n = int(s) #1
print(f'You entered {n}. 2*{n} = {2*n}.') #2
except ValueError:
print(f'{s} is not numeric.') #3
Compare character-based validation with try/except conversion, which also handles negative integers. section 8.7

