- Home
- /
- Python Data Conversion
Python Tutorial
Introduction
Python Data Types & Oper...
Python Strings
Python Lists
Python Tuples
Python Sets
Python Dictionaries
Conditional Statements
Python Loops
Python Functions
Python Modules
Python OOPS
Advanced Topics
File Handling
- Home
- /
- Python Data Conversion
Python Data Conversion
In Python, sometimes you need to change the type of a number. This process is called type conversion. It’s useful when working with different types of values in mathematical operations or data processing.
Converting int → float → complex
Let’s begin with an integer and convert it into other types:
score = -18
as_float = float(score) # Convert to float
as_complex = complex(score) # Convert to complex
print("Float:", as_float) # Output: -18.0
print("Complex:", as_complex) # Output: (-18+0j)
The float()
function adds a decimal point, while complex()
adds an imaginary part +0j
.
Converting float → int → complex
You can also convert a float to an integer, or a complex number:
price = 49.75
as_int = int(price) # Converts to whole number (drops decimal part)
as_complex = complex(price) # Adds imaginary part
print("Integer:", as_int) # Output: 49
print("Complex:", as_complex) # Output: (49.75+0j)
Note: int()
doesn’t round; it simply truncates the decimal part.
Complex to int or float?
Python does not allow direct conversion from complex to int or float, and trying to do so will result in an error.
z = 3 + 2j
# int(z) or float(z) will raise: TypeError
To convert a complex number, you’ll first need to extract its real part:
real_part = int(z.real)
print("Real as int:", real_part) # Output: 3
Summary
Use
float(x)
to convert an integer to a float.Use
complex(x)
to turn a number into a complex type.Use
int(x)
to convert a float to an integer (truncates decimal).You cannot directly convert complex numbers to
int
orfloat
.