Skip to content

Computer Science · Ch 5 — Getting Started with Python

Implicit Conversion

5.12.2

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 10 to the float 10.0 loses nothing — every integer has an exact float form.
  • Converting the float 20.0 to an int could destroy information (had it been 20.5, the .5 would 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 decidesExampleRisk of information loss
Implicit (coercion)The interpreter, automatically10 + 20.0 becomes 30.0None — promotion only happens when safe