Number data types store numeric values. There are three numeric types in Python.
The Python type() function is used to findout the datatype of a specified variable. In the below example, type() function is used to find out the datatype of numbers.
MyInt = 10 print(type(MyInt)) MyFloat = 10.5 print(type(MyFloat)) MyFloat = 7.5e2 print(type(MyFloat)) MyComplex = 5 + 5j print(type(MyComplex))
<class 'int'> <class 'float'> <class 'float'> <class 'complex'>
Python converts number data type automatically when an expression containing mixed numeric data types is evaluated.
MyInt = 10 MyFloat = 15.5 MyComplex = 5 + 5j NewNumber = MyInt + MyFloat print(NewNumber," belongs to ",type(NewNumber)) NewNumber = MyFloat + MyComplex print(NewNumber," belongs to ",type(NewNumber)) NewNumber = MyInt + MyFloat + MyComplex print(NewNumber," belongs to ",type(NewNumber))
25.5 belongs to <class 'float'> (20.5+5j) belongs to <class 'complex'> (30.5+5j) belongs to <class 'complex'>
Sometimes, It is required to convert explicitly from one numeric datatype to another numeric datatype according to the operator or function parameter. This can be achieved by using the constructor function of the given data type class.
z = int(10.5) print(z," belongs to ",type(z)) z = float(10) print(z," belongs to ",type(z)) z = complex(5.5) print(z," belongs to ",type(z)) z = complex(2, 3) print(z," belongs to ",type(z))
10 belongs to <class 'int'> 10.0 belongs to <class 'float'> (5.5+0j) belongs to <class 'complex'> (2+3j) belongs to <class 'complex'>