Standard Library

Number Parsing

int() and float() parse text into numbers and raise ValueError on bad input.

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.5
"42"int()42ValueError
int() turns text into a typed number; malformed input raises ValueError instead of guessing.

Pass a base when the text format says the number is not decimal.

Source

print(int("ff", 16))

Output

255

Catch 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'
40

Notes

See also

Run the complete example

Example code

Expected output

42
3.5
255
20
skip 'python'
40

Execution time appears here after you run the example.