1. 程式人生 > >[python] 從python2.x遷移到python3.x的常見操作

[python] 從python2.x遷移到python3.x的常見操作

  1. print 'something' > print('something')
  2. xrange() > range()
  3. 除法division
    python 2.x : 整數 / 整數
    python 3.x : 整數 // 整數
    這個很難發現,因為python弱型別。
    python2.x中/是classic division,和C++一樣,所以兩個整數運算元會有整數結果,特別是可以自動取整。在python3.x中/是浮點除法,結果是浮點數,//是整數除法。

    python 2.x : integer / integer
    python 3.x : integer // integer
    this bug is hard to find as we cannot check the types since python does not require explicit declaration.
    /
    in python 2.x is the class division the same as in C++. Hence two integers as operands result in an integer. If the inherent flooring feature is desired, awareness should be raised when transferring to python 3.x. In python 3, / is used as merely float division and will produce a float in the above case, so //
    should be used to replace it because it supports the integer division.