Standard Library
Number Parsing
Use int() for whole numbers and float() for decimal text. Parsed values are real numbers, not strings.
Source
print(int("42"))
print(float("3.5"))Output
42
3.5Pass a base when the text format says the number is not decimal.
Source
print(int("ff", 16))Output
255Catch ValueError at the input boundary when invalid text is normal and recoverable.
Source
texts = ["10", "python", "20"]
for text in texts:
try:
print(int(text) * 2)
except ValueError:
print(f"skip {text!r}")Output
20
skip 'python'
40Notes
int()andfloat()are constructors that also parse strings.int(text, base)makes non-decimal input explicit.- Catch
ValueErrorfor recoverable user input; do not hide unexpected data corruption.
See also
- prerequisite: Exceptions
- prerequisite: Strings
- prerequisite: Numbers
Run the complete example
Expected output
42
3.5
255
20
skip 'python'
40
Execution time appears here after you run the example.