Data Type Conversion In Python
Clear concept of data types conversion in python
Python Data Conversion Made Easy
In Python, sometimes we need to switch a number’s type — like turning an integer into a float or a complex number. This change of types is called type conversion. Let's dive into how to do it easily with examples!
1. Converting an Integer to a Float
If we want to turn an integer (a whole number) into a decimal (float), we use float()
.
Example:
num1 = -25
num2 = float(num1) # Converts -25 to -25.0
print(num2) # Output: -25.0
2. Converting an Integer to a Complex Number
To make an integer into a complex number, use the complex() function. Complex numbers have a real part and an imaginary part. Example:
num1 = -25
num3 = complex(num1) # Converts -25 to (-25+0j)
print(num3) # Output: (-25+0j)
3. Converting a Float to an Integer
To convert a float (like 8.4) to an integer, use int(). The int() function will round down, dropping the decimal part. Example:
num1 = 8.4
num2 = int(num1) # Converts 8.4 to 8
print(num2) # Output: 8
4. Converting a Float to a Complex Number
To turn a float into a complex number, use complex() again! Example:
num1 = 8.4
num3 = complex(num1) # Converts 8.4 to (8.4+0j)
print(num3) # Output: (8.4+0j)
Important Note:
Complex numbers cannot be directly converted to an integer or float, as they have both real and imaginary parts.