Python2.x vs 3.x Version Differences
\n\nPython's 3.0 version, often referred to as Python 3000 or Py3k, represents a significant upgrade from earlier versions of Python.
\n\nTo avoid carrying too much legacy baggage, Python 3.0 was designed without backward compatibility in mind.
\n\nMany programs written for earlier Python versions will not run correctly on Python 3.0.
\n\nTo accommodate existing programs, Python 2.6 was released as a transitional version. It largely uses Python 2.x syntax and libraries while considering migration to Python 3.0, allowing the use of some Python 3.0 syntax and functions.
\n\nNew Python programs are recommended to use Python 3.0 syntax.
\n\nUnless the execution environment cannot install Python 3.0 or the program itself uses third-party libraries that do not support Python 3.0. Currently, third-party libraries that do not support Python 3.0 include Twisted, py2exe, PIL, etc.
\n\nMost third-party libraries are actively working to be compatible with Python 3.0. Even if you cannot use Python 3.0 immediately, it is recommended to write programs compatible with Python 3.0 and then run them using Python 2.6 or Python 2.7.
\n\nThe changes in Python 3.0 are mainly in the following aspects:
\n\n\n\n
print Function
\n\nThe print statement is gone, replaced by the print() function. Python 2.6 and Python 2.7 partially support this form of print syntax. In Python 2.6 and Python 2.7, the following three forms are equivalent:
print "fish"\nprint ("fish") # Note the space after print\nprint("fish") # print() cannot have any other parameters\n\n\nHowever, Python 2.6 actually already supports the new print() syntax, as shown in the following example:
from __future__ import print_function\nprint("fish", "panda", sep=', ')\n\n\nIf a Python 2.x version wants to use the Python 3.x print function, you can import the __future__ package. This package disables the Python 2.x print statement and adopts the Python 3.x print function:
Example
\n\n>>>list=["a","b","c"]\n\n>>>print list # Python 2.x print statement\n\n['a','b','c']\n\n>>>from __future__ import print_function # Import __future__ package\n\n>>>print list # Python 2.x print statement is disabled, using it causes an error\n\n File "<stdin>", line 1\n\nprint list\n\n^\n\nSyntaxError: invalid syntax\n\n>>>print(list) # Using Python 3.x print function\n\n['a','b','c']\n\n>>>\n\n\nMany compatibility features designed for Python 2.x can be imported via the __future__ package.
\n\n
Unicode
\n\nPython 2 has ASCII str() type, and unicode() is separate and not a byte type.
Now, in Python 3, we finally have Unicode (utf-8) strings, and a bytes class: bytes and bytearrays.
Since Python 3.x source files use utf-8 encoding by default, using Chinese characters is more convenient:
\n\n>>> China = 'china'\n>>> print(China)\nchina\n\n\nPython 2.x
\n\n>>> str = "I love Beijing Tiananmen\n>>> str\n'xe6x88x91xe7x88xb1xe5x8cx97xe4xbaxacxe5xa4xa9xe5xaex89xe9x97xa8'\n>>> str = u"I love Beijing Tiananmen\n>>> str\nu'u6211u7231u5317u4eacu5929u5b89u95e8'\n\n\nPython 3.x
\n\n>>> str = "I love Beijing Tiananmen\n>>> str\n'I love Beijing Tiananmen'\n\n\n\n\n
Division
\n\nDivision in Python is quite sophisticated compared to other languages, with a complex set of rules. There are two division operators in Python: / and //.
First, let's talk about the / division:
In Python 2.x, / division works like in most languages we are familiar with, such as Java and C. Integer division results in an integer, completely ignoring the fractional part, while floating-point division retains the decimal part to produce a floating-point result.
In Python 3.x, / division no longer works this way. For integer division, the result will also be a floating-point number.
Python 2.x:
\n\n>>> 1 / 2\n0\n>>> 1.0 / 2.0\n0.5\n\n\nPython 3.x:
\n\n>>> 1/2\n0.5\n\n\nAs for // division, this is called floor division. It automatically performs a floor operation on the result of the division, and this behavior is consistent in Python 2.x and Python 3.x.
Python 2.x:
\n\n>>> -1 // 2\n-1\n\n\nPython 3.x:
\n\n>>> -1 // 2\n-1\n\n\nNote that it does not discard the fractional part but performs a floor operation. If you want to truncate the integer part, you need to use the trunc function from the math module.
Python 3.x:
\n\n>>> import math\n>>> math.trunc(1 / 2)\n0\n>>> math.trunc(-1 / 2)\n0\n\n\n\n\n
Exceptions
\n\nHandling exceptions in Python 3 has also changed slightly. In Python 3, we now use as as the keyword.
The syntax for catching exceptions has changed from except exc, var to except exc as var.
Using the syntax except (exc1, exc2) as var allows catching multiple categories of exceptions simultaneously. Python 2.6 already supports both syntaxes.
- \n
- In the 2.x era, all types of objects could be directly raised. In the 3.x era, only objects inheriting from
BaseExceptioncan be raised. \n - The 2.x
raisestatement uses a comma to separate the raised object type and arguments. The 3.x version eliminates this odd syntax; you can directly call the constructor to raise an object. \n
In the 2.x era, exceptions in code often performed tasks that normal control structures should handle, in addition to indicating program errors. In 3.x, it can be seen that designers have made exceptions more specialized, only to be used with exception catching statements when errors occur.
\n\nPython 2.x: Exception handling syntax uses a comma.
\n\ntry:\n # code\nexcept Exception, e:\n print e\n\n\nPython 3.x: Exception handling syntax uses as.
try:\n # code\nexcept Exception as e:\n print(e)\n\n\n\n\n
xrange() and range()
\n\nPython 2.x: range() returns a list, while xrange() returns a generator (more memory-efficient).
range(5) # Returns [0, 1, 2, 3, 4]\nxrange(5) # Returns an xrange object, generating numbers on demand\n\n\nPython 3.x: xrange() has been removed. range() returns a generator, saving memory.
range(5) # Returns an iterator, generating numbers on demand\n\n\n\n\n
Octal Literal Representation
\n\nOctal numbers must be written as 0o777; the old form 0777 is no longer allowed. Binary numbers must be written as 0b111.
A new bin() function has been added to convert an integer to a binary string. Python 2.6 already supports both syntaxes.
In Python 3.x, there is only one way to represent octal literals, which is 0o1000.
Python 2.x
\n\n>>> 0o1000\n512\n>>> 01000\n512\n\n\nPython 3.x
\n\n>>> 01000\n File "<stdin>", line 1\n 01000\n ^\nSyntaxError: invalid token\n>>> 0o1000\n512\n\n\n\n\n
Not Equal Operator
\n\nIn Python 2.x, there are two ways to write "not equal": != and <>.
In Python 3.x, <> has been removed, leaving only !=. Fortunately, I never had the habit of using <>.
\n\n
Removed repr Expression Backticks ``
\n\nIn Python 2.x, backticks `` ` `` functioned like the repr function.
In Python 3.x, this backtick syntax has been removed, allowing only the repr function. The purpose of this change is to make the code look clearer, right? However, I feel that the opportunity to use repr is rare, usually only during debugging. Most of the time, the str function is used to describe objects as strings.
\n\n
Several Modules Renamed (Based on PEP8)
\n\n| Old Name | \nNew Name | \n
|---|---|
| _winreg | \nwinreg | \n
| ConfigParser | \nconfigparser | \n
| copy_reg | \ncopyreg | \n
| Queue | \nqueue | \n
| SocketServer | \nsocketserver | \n
| repr | \nreprlib | \n
The StringIO module has now been merged into the new io module. Modules like new, md5, gopherlib, etc., have been removed. Python 2.6 already supports the new io module.
httplib, BaseHTTPServer, CGIHTTPServer, SimpleHTTPServer, Cookie, and cookielib have been merged into the http package.
The exec statement has been removed, leaving only the exec() function. Python 2.6 already supports the exec() function.
\n\n
5. Data Types
\n\n- \n
- Py3.X removed the
longtype. Now there is only one integer typeβint, but it behaves like thelongtype in 2.X. \n - A new
bytestype has been added, corresponding to the 8-bit string in 2.X. Here is how to define a bytes literal: \n
>>> b = b'china'\n>>> type(b)\n<type 'bytes'>\n\n\nThe str object and bytes object can be converted to each other using the .encode() (str -> bytes) or .decode() (bytes -> str) methods.
>>> s = b.decode()\n>>> s\n'china'\n>>> b1 = s.encode()\n>>> b1\nb'china'\n\n\n- \n
- The
.keys(),.items(), and.values()methods ofdictreturn iterators, while the previous functions likeiterkeys()have been deprecated. Also removed isdict.has_key(); useininstead. \n
\n\n
6. Standard Library Reorganization
\n\nPython 3.x: Some modules have been reorganized or renamed. For example, urllib and urlparse have been merged into urllib.
# Python 2.x\nimport urllib\nimport urlparse\n\n# Python 3.x\nimport urllib.parse\n\n\n\n\n
7. dict.iteritems() and dict.items()
\n\nPython 2.x: Dictionaries have items() and iteritems() methods. items() returns a list, while iteritems() returns an iterator.
d = {'a': 1, 'b': 2}\nd.items() # Returns [('a', 1), ('b', 2)]\nd.iteritems() # Returns an iterator over the dictionary\n\n\nPython 3.x: iteritems() has been removed. items() returns a dictionary view (i.e., an iterator).
d = {'a': 1, 'b': 2}\nd.items() # Returns dict_items([('a', 1), ('b', 2)])\n\n\n\n\n
8. Module __future__ Support
\n\nPython 3.x: Many Python 2.x features have been removed. If Python 2.x users want to use Python 3.x behavior in their code ahead of time, they can use __future__ imports for compatibility.
from __future__ import print_function\n\n\n9. Dictionary Ordering
\n\nPython 2.x: Dictionaries are unordered (order is not guaranteed).
\n\nPython 3.x: Dictionaries are ordered, preserving the insertion order of elements.
\n\n10. next() Method
\n\nPython 2.x: next() is a function, typically used with iter().
Python 3.x: next() is a built-in function. Its usage is similar to Python 2.x, but its parameters differ. Python 3.x supports setting a default value via next(iterator, default).
YouTip