Computer Science · Ch 5 — Getting Started with Python
Implicit Conversion
Implicit Conversion
Implicit conversion, also known as coercion, happens when data type conversion is done automatically by Python, without any instruction from the programmer.
An int meets a float
Watch what happens when an integer and a float are added:
# Implicit type conversion from int to float
num1 = 10 # num1 is an integer
num2 = 20.0 # num2 is a float
sum1 = num1 + num2 # sum of a float and an integer
print(sum1)
print(type(sum1))
30.0
<class 'float'>
The integer value in num1 was added to the float value in num2, and the result stored in sum1 was automatically a float — we never told the interpreter to convert anything. That is implicit data conversion at work.
Why float, and not int?
One may wonder: why did Python not convert the float to an integer instead, giving 30? The answer is type promotion. Whenever possible, Python performs an operation by converting the data into the wider-sized data type, so that the operation happens without any loss of information.
- Converting the int
10to the float10.0loses nothing — every integer has an exact float form. - Converting the float
20.0to an int could destroy information (had it been20.5, the.5would vanish).
So Python promotes the "narrower" type (int) up to the "wider" type (float), and the result takes the wider type.
Implicit versus explicit — the contrast
Together with the previous sub-section, the full picture of type conversion is:
| Who decides | Example | Risk of information loss | |
|---|---|---|---|
| Implicit (coercion) | The interpreter, automatically | 10 + 20.0 becomes 30.0 | None — promotion only happens when safe |