Quite often, there is a need to convert one data type to another, such as a float to an integer, or a string into a number and back. No worries! It is easy to achieve using built-in functions. However, there are some conversion rules to be learned. A string to a float is as follows:
>>> float(“2.5”)
2.5
A string to an integer is as follows:
>>> int(“45”)
45
A float to an integer and vice versa are as follows:
>>> int(4.521)
4
>>> float(5)
5.0
Booleans to integers, floats, and strings are as follows:
>>> int(True)
1
>>> float(False)
0.0
>>> str(True)
'True'
If Python cannot convert values, then it will raise an error:
>>> int(“2.5”)
File "<ipython-input-11-cf753495344d>", line 1
int(“2.5”)
^
SyntaxError...