LoginSignup
0
3

More than 5 years have passed since last update.

Python 2.x と 3.xの違い覚書

Last updated at Posted at 2018-03-14

input()関数の型

Python 2.x系では、input関数で取得した値は、適切な型に変換される。

python2.x
a, b = input(), input()
print(a+b)
# a=2, b=3 → 5と表示

Python 3.x系では、input関数で取得した値は、str型で取り扱われる。
数値として取り扱いたいときは、型変換する

python3.x
a, b = input(), input()
print(a+b)
# a=2, b=3 → 23と表示

a, b = int(input()), int(input())
print(a+b)
# a=2, b=3 → 5と表示

range関数の取り扱い

Python 2.x系では、rangeを変数で受けると、配列を取り込める

python2.x
a = range(5)

print(a)
# [0, 1, 2, 3, 4]

Python 3.x系では、range関数はrangeオブジェクトとして受け取られる。
配列として取り扱うとエラーがでる。
配列として取り扱うときは、list関数で変換すれば、配列として取り扱える。
(頂いたコメントを参考にして修正しました)

python3.x
a = range(5)
a[0] = 1
print(a)
# エラー
# TypeError: 'range' object does not support item assignment

a = list(range(5))
a[0] = 1
print(a)
# [1, 1, 2, 3, 4]
0
3
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
0
3