Division in Python 3 gives different result than in Python 2

后端 未结 3 622
北恋
北恋 2020-12-04 03:09

In the following code, I want to calculate the percent of G and C characters in a sequence. In Python 3 I correctly get 0.5, but on Python 2 I get 0

3条回答
  •  眼角桃花
    2020-12-04 03:58

    / is a different operator in Python 3; in Python 2 / alters behaviour when applied to 2 integer operands and returns the result of a floor-division instead:

    >>> 3/2   # two integer operands
    1
    >>> 3/2.0 # one operand is not an integer, float division is used
    1.5
    

    Add:

    from __future__ import division
    

    to the top of your code to make / use float division in Python 2, or use // to force Python 3 to use integer division:

    >>> from __future__ import division
    >>> 3/2    # even when using integers, true division is used
    1.5
    >>> 3//2.0 # explicit floor division
    1.0
    

    Using either of these techniques works in Python 2.2 or newer. See PEP 238 for the nitty-gritty details of why this was changed.

提交回复
热议问题