Python - Numeric Mixed types


You can mix numeric types. For instance, you can add an integer to a floating-point number:

40 + 3.14 

In mixed-type numeric expressions, Python converts operands up to the type of the most complicated operand, and then performs the math on same-type operands.

Python ranks the complexity of numeric types like so:

  • integers are simpler than floating-point numbers, which are simpler than complex numbers.

So, when an integer is mixed with a floating point, the integer is converted up to a floating-point value first, and floating-point math yields the floating-point result:


print( 40 + 3.14 )       # Integer to float, float math/result


You can force the issue by calling built-in functions to convert types manually:


print( int(3.1415) )     # Truncates float to integer 
print( float(3) )        # Converts integer to float


Related Topic