First page Back Continue Last page Overview Graphics

Casting in Python

A type can be explicitly changed from one to another type:

int()

float()

str()

There are situation, where this is necessary:

>>> x = '10'

>>> y = '7'

>>> print(x + y)

107

>>> print(int(x) + int(y))

17

>>> print(float(x) + float(y))

17.0

>>> x = "42"

>>> print(int(x))

42

>>> x = '42.0'

>>> print(float(x))

42.0

>>> print(int(float(x)))

42

>>> print(int(x))

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

ValueError: invalid literal for int() with base 10: '42.0'

>>>