When performing arithmetic operations, Python often needs to 'promote' the types involved to ensure compatibility.
Promotion means converting numbers to a common type. This ensures the computation is accurate.
For example, an integer will be promoted to a float if combined with a float. This is called type promotion.
- Integer (int), for whole numbers like
1
, 2
- Float (float), for decimal numbers like
1.0
, 2.0
- Complex (complex), for complex numbers like
1 + 2j
Python follows a specific hierarchy when promoting types:
This hierarchy means that in mixed-type expressions, Python will convert integers to floats first, then if needed to complex. In our case
1 + 2.0 + 3
, all integers will be promoted to floats.