Skip to main content
Engineering LibreTexts

9.30: Backwards Compatibility with Python Version 2

  • Page ID
    14650
  • The reason we call float() to convert bounceRate to a floating point number is simply so that this program will work in Python version 2. In Python version 3, the division operator will evaluate to a floating point value even if both of the operands are integers, like this:

    >>> # Python version 3
    ...
    >>> 10 / 5
    2.0
    >>> 10 / 4
    2.5
    >>>
    

    However, in Python version 2, the / division operator will only evaluate to a floating point value if one of the operands is also a floating point value. If both operands are integers, then Python 2’s division operator will evaluate to an integer value (rounding down if needed), like this:

    >>> # Python version 2
    ...
    >>> 10 / 5
    2
    >>> 10 / 4
    2
    >>>  10 / 4.0
    2.5
    >>>  10.0 / 4
    2.5
    >>>  10.0 / 4.0
    2.5 
    

    But if we always convert one of the values to a floating point value with the float() function, then the division operator will evaluate to a float value no matter which version of Python runs this source code. Making these changes so that our code works with older versions of software is called backwards compatibility. It is important to maintain backwards compatibility, because not everyone will always be running the latest version of software and you want to ensure that the code you write works with as many computers as possible.

    You can’t always make your Python 3 code backwards compatible with Python 2, but if it’s possible then you should do it. Otherwise, when people with Python 2 try to run your games will get error messages and think that your program is buggy.

    A list of some differences between Python 2 and Python 3 can be found at http://inventwithpython.com/appendixa.html.