Behavior of “round” function in Python

Could anyone explain me this pice of code:

>>> round(0.45, 1)
0.5
>>> round(1.45, 1)
1.4
>>> round(2.45, 1)
2.5
>>> round(3.45, 1)
3.5
>>> round(4.45, 1)
4.5
>>> round(5.45, 1)
5.5
>>> round(6.45, 1)
6.5
>>> round(7.45, 1)
7.5
>>> round(8.45, 1)
8.4
>>> round(9.45, 1)
9.4

Updated

I guess it is because of floating representation. Am I right?

Best answer

You are right. None of the numbers can be represented exactly. In some cases the fractional part is strictly greater than 0.45 and in some it is strictly less:

In [4]: ['%.20f' % val for val in (0.45, 1.45, 2.45, 3.45, 4.45, 5.45, 6.45, 7.45, 8.45, 9.45)]
Out[4]: 
['0.45000000000000001110',
 '1.44999999999999995559',
 '2.45000000000000017764',
 '3.45000000000000017764',
 '4.45000000000000017764',
 '5.45000000000000017764',
 '6.45000000000000017764',
 '7.45000000000000017764',
 '8.44999999999999928946',
 '9.44999999999999928946']

This explains the seemingly inconsistent rounding.