Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Khác biệt quan trọng giữa Python 2.x và Python 3.x


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ăngPython 2Python 3
Unicodestr=bytes, unicode=textstr=unicode, bytes=bytes
range()Trả về listTrả về range object (lazy)
dict.keys()Trả về listTrả về view (lazy)
__next__()next() method__next__() method
Metaclass__metaclass__ attrmetaclass= 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ũ.