preface
If you’re new to Python, you probably learned Python 3.x directly. There will be no contact with the Python 2.x version. It has also been officially announced that Python 2.x will cease maintenance in 2020. I also recommend beginners go straight to Python 3.x. But let’s take a look at some of the changes between Python 3.x and Python 2.x to give you a better understanding of Python. And in many interviews, interviewers will ask the difference between Python 2.x and Python 3.x. Here are some of the major changes in Python 3.0.
Py3K
Version 3.0 of Python is often referred to as Python 3000, or Py3K for short.
In order to accommodate existing programs, Python 2.6 is a transitional release that basically uses Python 2.x syntax and libraries, while allowing for a migration to Pythn 3.0 that allows some Python 3.0 syntax and functions to be used.
Python 3.0 changes in the following areas:
1 the print function
The 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"
print ("fish") Note that there is a space after print
print("fish") # print() cannot take any other arguments
Copy the code
Then, Python 2.6 actually supports the new print() syntax:
from __future__ import print_function
print("fish"."panda", sep=",")
Copy the code
2 Unicode
Python 2 has the ASCII STR () type, and Unicode () is a separate, not byte type.
Now, in Python 3, we finally have Unicode(UTF-8) strings, and one byte class: Byte and ByteArrays.
Since the Python 3.x source file uses THE UFT-8 encoding by default, this makes the following code legal:
= > > > China'china'
>>> printChinaCopy the code
Python 2.x
>>> str = 'I love Tiananmen In Beijing'
>>> str
'\xe6\x88\x91\xe7\x88\xb1\xe5\x8c\x97\xe4\xba\xac\xe5\xa4\xa9\xe5\xae\x89\xe9\x97\xa8'
>>> str = u'I love Tiananmen In Beijing'
>>> str
u'\u6211\u7231\u5317\u4eac\u5929\u5b89\u95e8'
Copy the code
Python 3.x
>>> str = "I love Tiananmen Square in Beijing"
>>> str
'I love Tiananmen In Beijing'
Copy the code
3. Division
Division in Python is much more sophisticated than in other languages, with a complex set of rules. There are two operators for division in Python, / and // To start with/division:
In Python 2.x/division is similar to most familiar languages, such as Java and C. The result of dividing an integer is an integer, and the decimal part is completely ignored. Floating-point division preserves the decimal part to get a floating-point result.
In Python 3.x/division no longer does this, and division between integers results in floating-point numbers as well.
Python 2.x
>>> 1/2 0 >>> 1.0/2.0 0.5Copy the code
Python 3.x
> > > 1/2 0.5Copy the code
In the case of // division, which is called floor division, a floor operation is automatically performed on the result of division, which is consistent in Python 2.x and Python 3.x.
While floor division refers to a rounded integer that returns a number, there is a floor function in Python that cannot be accessed directly, requiring importing the Math module and calling the method through a static object. Here’s an example:
import math # This will import math module
print "math.floor(-45.17) : ", math. Floor (45.17)Copy the code
Output result:
Math. Floor (45.17) : 46.0Copy the code
python 2.x:
>>> -1 // 2-1Copy the code
Note that instead of discarding the decimal part, you perform the floor operation. To truncate the decimal part, you need to use the Trunc function of the Math module
python 3.x
>>> import math
>>> math.trunc(1 / 2)
0
>>> math.trunc(-1 / 2)
0
Copy the code
4 abnormal
Handling exceptions has also changed slightly in Python 3, where we now use as as the keyword.
The syntax for catching exceptions was changed from except exc, var to except exc as var.
Using the syntax except (exc1, exc2) as var, you can catch multiple types of exceptions at the same time. Python 2.6 already supports both syntaxes.
-
1. In the 2.x era, all types of objects could be thrown directly. In the 3.x era, only objects that inherit from BaseException could be thrown.
-
2. 2. X raise statements use commas to separate thrown object types from arguments. 3.
In the era of 2.x, exceptions in code not only indicate program errors, but also often do some things that ordinary control structures should do. As can be seen from 3.x, the designer makes exceptions more specific, and only in the case of errors, can we use exception capture statements to deal with them.
5 xrange
The use of xrange() to create iterators is very popular in Python 2. For example, a for loop or a list/set/dictionary derivation.
This behavior is very generator like (e.g. Lazy evaluation “). But this xrange-iterable is infinite, which means you can iterate over it indefinitely.
Because of its lazy evaluation, the xrange() function is faster than range() if you have to go through it only once (for example). However, it is not recommended that you iterate more than once, since the generator starts from scratch each time.
Lazy evaluation: Lazy evaluation, or lazy evaluation, in which an expression is not evaluated immediately after it is bound to a variable, but is evaluated when it is used.
What it does: This feature can solve some large or even infinite collection lists. One benefit of delayed evaluation is the ability to build computable infinite lists without infinite loops or size problems that impede computation.
Many methods in Python do not return a list directly, but instead return an iterable generator object, which is Python’s lazy evaluation.
In Python 3, range() is implemented like xrange() so that a dedicated Xrange () function no longer exists (xrange() throws named exceptions in Python 3).
import timeit
n = 10000
def test_range(n):
return for i in range(n):
pass
def test_xrange(n):
for i in xrange(n):
pass
Copy the code
Python 2
print 'Python', python_version()
print '\ntiming range()'
%timeit test_range(n)
print '\n\ntiming xrange()'%timeit test_xrange(n) Python 2.7.6 Timing range() 1000 Loops, best of 3: Loop Timing Xrange () 1000 Loops, Best of 3: 350 µs per loopCopy the code
Python 3
print('Python', python_version())
print('\ntiming range()'Timeit test_range(n) Python 3.4.1 Timing range() 1000 loops, best of 3: 520 µs per loopCopy the code
print(xrange(10))
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-5-5d8f9b79ea70> in <module>()
----> 1 print(xrange(10))
NameError: name 'xrange' is not defined
Copy the code
6 octal literal representation
Octal numbers must be written as 0o777 instead of 0777. Binary must be written as 0b111.
A 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, and that is 0o1000.
pyhon 2.x
>>> 0o1000
512
>>> 01000
512
Copy the code
python 3.x
>>> 01000
File "<stdin>", line 1
01000
^
SyntaxError: invalid token
>>> 0o1000
512
Copy the code
7 inequality operator
There are not two ways to write Python 2.x! = and < >
Python 3.x removes <>, only! Theta is one way of writing it.
Repr expression ‘ ‘is removed
Backquotes’ ‘in Python 2.x are equivalent to the repr function
Python 3.x removes this notation and allows only the repr function.
What a repr is: The repr() function converts an object into a form that the interpreter can read, returning a string of objects.
9 + modules renamed (according to PEP8)
Httplib, BaseHTTPServer, CGIHTTPServer, SimpleHTTPServer, Cookie, cookielib are merged into the HTTP package. The StringIO module is now incorporated into the new IO module. New, MD5, gopherlib and other modules were removed. Python 2.6 already supports new IO modules.
The exec statement is removed, leaving only the exec() function. Exec () is already supported in Python 2.6.
10 Data Types
1) Py3.X has removed long and now has only one integer — int, but it behaves like the 2.X version of Long.
2) New bytes type, corresponding to the octet in version 2.x. Define a bytes literal as follows:
>>> b = b'china'
>>> type(b)
<type 'bytes'>
Copy the code
STR objects and bytes objects can be converted to each other using the.encode() (STR -> bytes) or.decode() (bytes -> STR) methods.
>>> s = b.decode()
>>> s
'china'
>>> b1 = s.encode()
>>> b1
b'china'
Copy the code
Dict’s.keys(),.items, and.values() methods return iterators, while previous functions such as iterkeys() are deprecated. Also removed is dict.has_key(), which is replaced by in.
11 Opening a File
There are two original opening methods:
file( ..... ) Or open (...).Copy the code
Now it can only be used
open(......)
Copy the code
12 Enter a string from the keyboard
The original:
raw_input("Warning message")
Copy the code
Now:
input("Warning message")
Copy the code
In Python2.x, both raw_input() and input() exist, where the difference is:
-
Raw_input () : Treats all input as a string and returns a string type
-
Input () : can only accept “numeric” input, has its own properties for pure numeric input, it returns the type of the number entered (int, float)
In Python3.x, raw_input() and input() are combined to remove raw_input(), leaving only the input() function, which accepts arbitrary input, treats all input as strings by default, and returns a string type.
Please follow the wechat public account “Crazy Sea” to share Python dry materials every day, and reply to the background “Python Materials” to get the latest Python tutorials.