Python automatically converts a smaller data type to a larger data type.
a = 5 # int
b = 2.0 # float
c = a + b # Result: 7.0 (float)
print(type(c)) # Output: <class 'float'>
Done manually using built-in functions.
Function | Converts To | Example |
---|---|---|
int() |
Integer | int("10") → 10 |
float() |
Floating-point | float("5") → 5.0 |
complex() |
Complex number | complex("2+3j") → 2+3j |
Function | Converts To | Example |
---|---|---|
str() |
String | str(100) → "100" |
list() |
List | list("abc") → ['a','b','c'] |
tuple() |
Tuple | tuple([1, 2]) → (1, 2) |
set() |
Set | set([1, 1, 2]) → {1, 2} |
dict() |
Dictionary | dict([(1,'a'), (2,'b')]) |
Not all conversions are allowed. E.g. int("abc")
throws an error.
Use type()
to check a variable's current data type.