Python 3.x (ra mắt 2008) có nhiều thay đổi breaking so với 2.x (EOL 2020). Dưới đây 4 điểm chính.
1. Input: raw_input() → input()
# Python 2 a = int(raw_input()) # Python 3 a = int(input()) # Note: Py2 input() = eval(raw_input()) - nguy hiểm!
2. Print: Statement → Function
# Python 2
print "tutorialspoint"
print "a", "b", # Dấu phẩy cuối -> không newline
# Python 3
print("tutorialspoint")
print("a", "b", end=" ") # sep, end parameters
3. Phép chia: Integer division → True division
# Python 2 7 / 4 # 1 (int division) 7 // 4 # 1 (floor division) # Python 3 7 / 4 # 1.75 (true division - float) 7 // 4 # 1 (floor division)
4. Exception Handling: comma → as
# Python 2
try:
pass
except NameError, err:
print err, 'Error Caused'
# Python 3
try:
pass
except NameError as err:
print(err, 'Error Caused')
Các thay đổi quan trọng khác
| Tính năng | Python 2 | Python 3 |
|---|---|---|
| Unicode | str=bytes, unicode=text | str=unicode, bytes=bytes |
| range() | Trả về list | Trả về range object (lazy) |
| dict.keys() | Trả về list | Trả về view (lazy) |
| __next__() | next() method | __next__() method |
| Metaclass | __metaclass__ attr | metaclass= kwarg |
Kết luận
Python 2 đã EOL. Mọi dự án mới bắt buộc dùng Python 3. Công cụ 2to3 hỗ trợ chuyển đổi code cũ.