3.2.1. Difference between integers and floats#

Usually, floats and integers fulfil different roles:

Floats are used to represent real, physical values:

  • A force in newtons

  • A distance in meters

  • A power in watts

  • An angle in radians

  • etc.

Integers are used to represents ranks, indexes, counts, etc:

  • An index in a list (e.g, 5th value of a list)

  • A number of repetitions

  • A number of events

  • The size of a matrix

  • etc.

When we create a new numeric variable, the variable is defined:

  • as a float if its literal value contains a decimal point

  • as an int if its literal value contain a decimal point

an_int = 3
a_float = 3.1

The type of an existing variable can be known with the function type:

print(type(an_int))
print(type(a_float))
<class 'int'>
<class 'float'>

or isinstance:

print(isinstance(an_int, int))  # Is it an integer?
print(isinstance(an_int, float))  # Is it a float?
True
False

A variable can be converted from an int to a float using the float() function:

float(an_int)
3.0

A variable can be converted from a float to an int using the int() function. Please note, however, that the decimal component of the number is lost:

int(a_float)
3