Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

ความแตกต่างระหว่าง Python 2.x และ Python 3.x

Python 2 จบการสนับสนุน (EOL) ตั้งแต่ 2020 แต่โค้ดเก่ายังคงมีอยู่ บทความนี้สรุปความแตกต่างหลักเพื่อช่วย Migration

1. print: Statement → Function

# Python 2
print 'Hello, World!'
print 'text', ; print 'more'  # คั่นด้วย comma, semicolon

# Python 3
print('Hello, World!')
print('some text,', end='')
print('some more text here')

2. Integer Division

# Python 2
3 / 2   # 1 (floor)
3 // 2  # 1
3 / 2.0 # 1.5

# Python 3
3 / 2   # 1.5 (true division)
3 // 2  # 1 (floor)
3 / 2.0 # 1.5

Python 2: ใช้ from __future__ import division เพื่อให้ / ทำงานแบบ Python 3

3. Unicode Strings

# Python 2
type(u'unicode')   # 
type('bytes')       # 
'hello' + b'world'  # OK (auto decode)

# Python 3
type('unicode')     #  (UTF-8 default)
type(b'bytes')      # 
'hello' + b'world'  # TypeError: must be str, not bytes

4. Exception Syntax

# ทั้ง 2 รุ่น
raise IOError("error message")

# Python 2 เท่านั้น (SyntaxError ใน Py3)
raise IOError, "error message"

5. List Comprehension Variable Leak

# Python 2
i = 1
[i for i in range(5)]
print(i)  # 4 (leak!)

# Python 3
i = 1
[i for i in range(5)]
print(i)  # 1 (ปลอดภัย)

ความแตกต่างอื่นๆ

  • range() ใน Py3 คืน iterator (ลด RAM), Py2 คืน list
  • dict.keys(), .values(), .items() คืน view ไม่ใช่ list
  • xrange() หายไปใน Py3 (ใช้ range() แทน)
  • __next__() แทน .next()
  • Default encoding เป็น UTF-8 ใน Py3

สรุป: ใช้ Python 3 สำหรับโปรเจกต์ใหม่ทุกโปรเจกต์