Skip to main content

3.13) Operations: Avoiding Issues


Operations work on integers, floating numbers and many more types of objects. The result of the operation will normally be the same type as the numbers, or objects, in the operation.

Integer divisions:

>>> 2/3

The division of two integers will give an integer in Python 2, but a float in Python 3. To avoid a problem, remember to use floating numbers in a division:

>>> 2.0/3.0

Note: in Python 3.0 and above, if you want the division of integers to return a float, use the floor division (i.e. '//') if you want the result to be truncated to an integer.

If you mix integers and floats in operations, integers will be converted to floats:

>>> 2/3.0
0.6666666666666666

This can cause confusion when reading programs. I recommend you use the int() and float() functions to change the type of your variables in your operation:

>>> float(2)/3.0
0.6666666666666666