Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

Type conversion

A type constructor converts a value according to its own rules and raises an exception for unsupported input.

Version: Python 3.14; repository image, production runtime not attested

Syntax

quantity = int(text, 10)
whole = int(number)

A type constructor converts a value according to its own rules and raises an exception for unsupported input.

int parses integral text in the specified base and truncates a floating-point value toward zero. Text with a decimal point is not an integer literal for int. bool tests truthiness, so the nonempty string 'False' is true.

The results are 17, ValueError, -2 and TypeError for None.

assert int('ff',16)==255 and int(-2.8)==-2
assert int('010')==10
try: int('010',0)
except ValueError: pass
else: raise AssertionError
assert bool('False') and not bool('')

Examples

for value in (" 017 ", "-2.8", -2.8, None):
    try:
        print(int(value))
    except (ValueError, TypeError) as error:
        print(type(error).__name__)

Result

17
ValueError
-2
TypeError

The results are 17, ValueError, -2 and TypeError for None.

Sources