起因
在用python2解釋器運行python3代碼的時候,出現了bug。debug後發現是因爲python3中的/ 原本表示 精確除法,卻被python2解釋器解釋成了 地板除,最終導致了錯誤。因此我上網查閱了相關資料,並總結如下表:
總結
version | / | // |
---|---|---|
py2 | 整數除法時爲地板除,浮點數除法時爲精確除 | 地板除 |
py3 | 精確除法 | 地板除 |
Test
x = y = 10 x /= 2 # 精確除 y //= 2 # 地板除 print(x, type(x)) # 5.0 <class 'float'> print(y, type(y)) # 5 <class 'int'>
user@user:~$ python Python 2.7.13 |Anaconda 2.4.1 (64-bit)| (default, Dec 20 2016, 23:09:15) [GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux2 Type "help", "copyright", "credits" or "license" for more information. Anaconda is brought to you by Continuum Analytics. Please check out: http://continuum.io/thanks and https://anaconda.org >>> 9/2 4 >>> 9.0/2 4.5 >>> 9//2 4 >>> 9.0//2 4.0 >>> float(9)/2 4.5 >>> from __future__ import division >>> 9/2 4.5 >>> >>> [3]+ Stopped python >>> >>> user@user:~$ python3 Python 3.4.3 (default, Nov 17 2016, 01:08:31) [GCC 4.8.4] on linux Type "help", "copyright", "credits" or "license" for more information. >>> 9/2 4.5 >>> 9//2 4 >>> 9.0//2 4.0 >>>