Python Numbers Type Conversion
Python number datatype is used for numeric values. Number object is created when you give the numeric value to the variables.There are three different types of numeric types are available in Python.They are Integers, Floats and Complex numbers. we can easily convert one numeric type with another type in Python.
The Python tutorial on Techtuts provides an information about Python and Python 3 from the basis to high level. This tutorial provides a good understanding about the Python and Python for Technical, Non-Technical People, College Students and Working Professionals. Given examples are an easy to write and simple to practice by yourself.
In this tutorial you will learn about the Python and Python3. This tutorial includes an Introduction, Python Environment Setup, Variables, Data types , Control flow Statements, Loops, Functions, Data Structures, Modules ,Files, Classes, Python Web Frameworks etc
Python has built - in methods/functions for converting type from one to another. Here we are going to learn about how to convert one data type to another type in Python numeric types. There are three methods/functions are availbale in Python int(), Float(), complex()
int()
The int() is used converting any type to integer data type.
>>> a='1'
>>> b=int(a)
>>> print(type(a))
<class 'str'>
>>> print(type(b))
<class 'int'>
>>> print(a)
1
>>> print(b)
1
>>> a=1.2345
>>> b=int(a)
>>> print(type(a))
<class 'float'>
>>> print(type(b))
<class 'int'>
>>> print(a)
1.2345
>>> print(b)
1
float()
The float() is used converting any type to float data type.
>>> a ='1.345'
>>> print(type(a))
<class 'str'>
>>> b=float(a)
>>> print (type(b))
<class 'float'>
>>> print(b)
1.345
>>> a='1'
>>> b=float(a)
>>> print(b)
1.0
complex()
The complex() is used converting any type to complex data type.
>>> a="1+2j"
>>> print(type(a))
<class 'str'>
>>> print(a)
1+2j
>>> b=complex(a)
>>> print(type(b))
<class 'complex'>
>>> print(b)
(1+2j)
>>>