Why does the tip function produce different results in Python 2 and 3?

Question

When the tip() function is implemented according to the provided hint in this exercise, the values returned by the function differ if the code is executed using Python 2 versus Python 3. Why is that?

Answer

The difference is in the handling of division between the two version of Python. The hint states that the percentage should be divided by 100. In Python 3, division is done using floating point math which preserves any fractional portion. In Python 2, division is done using integer math which drops any fractional component unless one of the things being divided is a floating point number. To make the code equivalent between the two versions, the percentage should be divided by 100.0 or float(100) to ensure that the division is done correctly in Python 2.

5 Likes

When we have a number literal (given it is integer) in Python we can make it into a float by adding a dot.

>>> print (5.)
5.0
>>> 

The same does not apply to variables. They are not literal but referenced. We can use arithmetic to change their type.

>>> a = 5
>>> print (a + 0.0)
5.0

This is known as coercion and it takes a lot of clock ticks to pull off. That’s perhaps why Python 3 opted to make the integer an option, rather than the norm.

a / b in Python 2

is

a // b in Python 3
3 Likes