1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

python2と3では"1/2"の答えが違う

Last updated at Posted at 2019-12-06

python2と3では整数同士の割り算の答えが違います。

python2
>>> 1/2
0
python3
>>> 1/2
0.5    

python2とpython3の両方で動きうるコードを設計するなら、
1/2 = 0.5を期待する場合:

python2or3
>>> 1./2.
0.5

1/2 = 0を期待する場合:

python2or3
>>> int(1/2)
0

こんな感じにしとけばいいですね。

追記

__future__モジュールを使うことで、除算がpython2系でもpython3系と同じ動作をするようにできるようです。__future__モジュールにはpython2系とpython3系の互換性を補完する機能が備わっており、その中のdivisionをimportします。

python2or3

from __future__ import division

print(1/2)   # => 0.5
print(1//2)  # => 0

参考

1
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?