3??. of Python Version 0, often referred to as Python3000, or simply py3k. This is a large upgrade relative to earlier versions of Python.
In order not to bring in too much of a burden, Python3.0 in the design of the time did not consider the downward compatibility. Many of the programs designed for early Python versions are not performing properly on Python 3.0. To take care of the existing program, Python 2.6, as a transitional version, basically uses the syntax and library of Python 2.x, taking into account the migration to Python 3.0, allowing the use of some of the syntax and functions of Python 3.0.
The new Python program recommends using the Python3.0 version of the syntax. Unless the execution environment cannot install Python3.0 or the program itself uses a third-party library that does not support Python 3.0. Currently does not support Python 3.0 third-party library has twisted, py2exe, PiL and so on.
Most third-party libraries are striving to be compatible with Python version 3.0. Even if Python 3.0 is not immediately available, it is recommended that you write a program that is compatible with Python version 3.0 and then execute it using Python 2.6, Python 2.7来.
The changes in Python 3.0 are mainly in the following areas:
Print function
The print statement is gone and replaced by the print () function. Python2.6 and Python2.7 support this form of print syntax in part. In Python 2.6 and Python 2.7, the following three forms are equivalent:
print "fish"print ("fish") #注意print后面有个空格print("fish") #print()不能带有任何其它参数
Unicode
In Python2, there are two types of string data. A plain old text: the "str" object, which stores bytes. If you use a "u" prefix, you will have a "Unicode" object that stores the code points. In a Unicode string, you can use the backslash u (u) to insert any Unicode code point. Now, in Python3, we end up with a Unicode (Utf-8) string, and a byte class: Byte and Bytearrays.
Since the python3.x source file uses Utf-8 encoding by default, this makes the following code legal:
>>> 中国 = ‘china‘ >>>print(中国) china
Python 2.x
>>> str = "我爱北京天安门">>> str‘\xe6\x88\x91\xe7\x88\xb1\xe5\x8c\x97\xe4\xba\xac\xe5\xa4\xa9\xe5\xae\x89\xe9\x97\xa8‘>>> str = u"我爱北京天安门">>> stru‘\u6211\u7231\u5317\u4eac\u5929\u5b89\u95e8‘
Python 3.x
>>> str = "我爱北京天安门">>> str‘我爱北京天安门‘
Division operation
The division in Python is more sophisticated than other languages and has a very complex set of rules. The division in Python has two operators,/and//
First/Division:
In Python 2.x/division is similar to most of the languages we are familiar with, such as Java AH C Ah, the result of dividing an integer is an integer, the fractional part is completely ignored, and the floating-point division retains the part of the decimal point to get the result of a floating-point number.
In Python 3.x/division no longer does this, and the result is a floating-point number for dividing between integers.
Python 2.x:
>>> 1 / 20>>> 1.0 / 2.00.5
Python 3.x:
>>> 1/20.5
For//Division, this division, called Floor division, will automatically perform a floor operation on the result of division, consistent in Python 2.x and Python 3.x.
Python 2.x:
>>> -1 // 2-1
Python 3.x:
>>> -1 // 2-1
Note that instead of discarding the fractional part, the floor operation is performed, and if you want to intercept the fractional 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
Abnormal
Handling Exceptions in Python 3 has also changed slightly, and in Python 3 we now use as as keywords. The syntax for catching exceptions is changed by except Exc, Var to except Exc as Var. Use the syntax except (EXC1, Exc2) as Var to capture multiple categories of exceptions at the same time. Python 2.6 already supports both of these syntaxes.
- In the 2.x era, all types of objects can be thrown directly, in the 3.x era, only objects that inherit from Baseexception can be thrown.
- The 2.x raise statement uses commas to throw object types and parameters apart, and 3.x cancels the writing of this wonderful work, directly calling the constructor to throw the object.
In the 2.x era, exception in the code in addition to the program error, but also often do something common control structure should do, in 3.x can be seen, the designer let the exception becomes more exclusive, only in the case of errors can be used to deal with the exception capture statement.
Xrange
The use of xrange () to create iterative objects in Python 2 is very popular. For example, a for loop or a list/set/dictionary derivation. This behaves much like a generator (e.g.. "Lazy evaluation"). But this xrange-iterable is infinite, meaning you can traverse infinitely. Because of its lazy evaluation, if you must not simply not traverse it once, the xrange () function is faster than range (for example for loops). However, it is not recommended that you repeat iterations more than once, because the generator starts from scratch each time.
In Python 3, range () is implemented like xrange () so that a specialized xrange () function no longer exists (xrange () throws a named exception in Python 3).
octal literal representation
Octal number must be written 0o777, the original form 0777 can not be used, the binary must be written in 0b111. A new Bin () function is added to convert an integer into a binary string. Python 2.6 already supports both of these syntaxes. In Python 3.x, there is only one way to represent octal literals, which is 0o1000.
Python 2.x
>>> 0o1000512>>> 01000512
Python 3.x
>>> 01000 File "<stdin>", line 1 01000 ^SyntaxError: invalid token>>> 0o1000512
Inequality operator
Python 2.x does not equal two ways!! = and <>
Python 3.x is stripped of <> only! = a notation
Removed the repr expression '
The function str () is used to convert a value into a form suitable for human reading, while REPR () translates into a form for the interpreter to read. The inverse quotation mark in Python 2.x is equivalent to the function of repr. Python 3.x is stripped of this notation, allowing only the REPR function to be used
python2.x
>>> `"abc"`"‘abc‘">>> repr("abc")"‘abc‘"
python3.x
In [25]: repr("abc")Out[25]: "‘abc‘"In [26]: `"abc"` File "<ipython-input-26-1d8e11730830>", line 1 `"abc"` ^SyntaxError: invalid syntax
Multiple modules are renamed (according to PEP8)
the old name |
new name. |
_winreg |
WinReg |
Configparser |
Configparser |
Copy_reg |
Copyreg |
Queue |
Queue |
Socketserver |
Socketserver |
Repr |
Reprlib |
The Stringio module is now incorporated into the new IO module. Modules such as new, MD5, gopherlib, etc. are removed. Python 2.6 has support for new IO modules. Httplib, Basehttpserver, Cgihttpserver, Simplehttpserver, cookies, Cookielib are incorporated into the HTTP package. The EXEC statement is canceled and only the EXEC () function is left.
Data type
1) py3.x removed the long type and now has only one integer--int, but it behaves like 2. X version of Long
2) added the bytes type, corresponding to 2. X version of the eight-bit string, define a bytes literal method as follows:
>>> b = b‘china‘ >>> type(b) <type ‘bytes‘> str对象和bytes对象可以使用.encode() (str -> bytes) or .decode() (bytes -> str)方法相互转化。>>> s = b.decode() >>> s ‘china‘ >>> b1 = s.encode() >>> b1 b‘china‘
3) Dict. Keys (),. Items, and. Values () methods return iterators, and functions such as the previous iterkeys () are discarded. Also remove the Dict.has_key (), can be replaced with in.
Parsing the user's input via input ()
Python 3 improves the input () function so that the function will always store the user's input as a str object. In Python2, in order to avoid some risky behavior of reading non-string types, you have to use Raw_input () instead of input ().
Python 2.x
Python 2.7.6[GCC 4.0.1 (Apple Inc. build 5493)] on darwinType "help", "copyright", "credits" or "license" for more information.>>> my_input = input(‘enter a number: ‘)enter a number: 123>>> type(my_input)<type ‘int‘>>>> my_input = raw_input(‘enter a number: ‘)enter a number: 123>>> type(my_input)<type ‘str‘>
Python 3.x
Python 3.4.1[GCC 4.2.1 (Apple Inc. build 5577)] on darwinType "help", "copyright", "credits" or "license" for more information.>>> my_input = input(‘enter a number: ‘)enter a number: 123>>> type(my_input)<class ‘str‘>
Next () function and the. Next () method
Next () returns the next item of the iterator. Because the next () (. Next ()) function (method) is often used, it is also mentioned that another syntax change (implementation has also been changed): In Python2.7.5, both the function form and the method form can be used, and in Python3, only the next () function (attempting to invoke the. Next () method will trigger Attributeerror).
Python 2.x
>>> my_generator = (letter for letter in ‘abcdefg‘)>>> next(my_generator)‘a‘>>> my_generator.next()‘b‘
Python 3.x
In [36]: my_generator = (letter for letter in ‘abcdefg‘) ...:In [37]: next(my_generator) ...:Out[37]: ‘a‘In [38]: my_generator.next() ...:---------------------------------------------------------------------------AttributeError Traceback (most recent call last)<ipython-input-38-0ac0f88aeec6> in <module>()----> 1 my_generator.next()AttributeError: ‘generator‘ object has no attribute ‘next‘
Map, filter, and reduce
Map () maps the specified sequence according to the provided function. The first parameter function calls a function function with each element in the parameter sequence, returning a new list containing the return value of each function.
Map () function syntax:
Map (function, iterable, ...)
Parameters
Function--functions, with two parameters
Iterable--one or more sequences
The filter () function is used to filter the sequence, filter out elements that do not meet the criteria, and return a new list of eligible elements. The two parameters are received, the first is a function, the second is a sequence, each element of the sequence is passed as a parameter to the function, and then returns True or False, and finally the element that returns true is placed in the new list.
Syntax for the filter () method:
Filter (function, iterable)
Parameters
Function-------judging functions.
Iterable--Can iterate over objects.
These three functions are called function-programming representatives. There are also great differences in python3.x and python2.x. First we simply enter the map and filter in the python2.x interaction, and see that they are of the type built-in function (built-in functions):
>>> map<built-in function map>>>> filter<built-in function filter>>>>
The result types that they output are lists:
>>> map(lambda x:x *2, [1,2,3])[2, 4, 6]>>> filter(lambda x:x %2 ==0,range(10))[0, 2, 4, 6, 8]>>>
In Python 3.x They're not like this:
>>> map<class ‘map‘>>>> map(lambda x:x *2, [1,2,3])<map at 0x10d7e32e8>>>> filter<class ‘filter‘>>>> filter(lambda x:x % 2 == 0, range(10))<filter object at 0x10d8bd3c8>>>>
First they change from a function to a class, and secondly, their return result is an iterative object from the original list, and we try to use the next function to iterate manually:
>>> f =filter(lambda x:x %2 ==0, range(10))>>> next(f)0>>> next(f)2>>> next(f)4>>> next(f)6
For the relatively high-end reduce function, it is no longer part of the built-in in Python 3.x and is moved to the Functools module.
The difference between python2.x and python3.x