Converting the data types

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: invalid character in identifier
Python data types are strong. Python does not convert them implicitly under the hood, as some other languages, such as JavaScript, do. There is one exception to that: Booleans can behave as integers, specifically 0 (False) and 1 (True). This is a direct result of a not-so-hidden secret.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset