Division in Python 3 gives different result than in Python 2

后端 未结 3 636
北恋
北恋 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:49

    In python2.x / performs integers division.

    >>> 3/2
    1
    

    To get desired result you can change either one of the operands to a float using float():

    >>> 3/2.      #3/2.0
    1.5
    >>> 3/float(2)
    1.5
    

    or use division from __future__:

    >>> from __future__ import division
    >>> 3/2
    1.5
    

提交回复
热议问题