This article mainly introduces the new features of Python3.x and 10 major changes. This article explains the concept of Python3.0 by guidovanrosum, the father of Python, and some changes of Python3, such as print () andexec () functions, integers, division, and input () replace raw_input (). For more information, see Python 3.x. The initial version is Python 3.0. The latest version is 3.3.3.
Guido van rosum, father of Python, talked about the idea of Python 3.0:
Until backward compatibility is broken, many defects and errors cannot be fixed. Therefore, Python 3000 will be the first version to discard backward compatibility, with the aim of moving Python forward to the best language.
Python 3.0 is often called Python 3000 or Py3k. Compared with earlier versions of Python, this is a major upgrade. In order not to bring too much effort into it, Python 3.0 was not designed with backward compatibility considerations. Many programs designed for earlier versions of Python cannot run properly on Python 3.0. To take care of existing programs, Python 2.6, as a transitional version, basically uses Python 2. x syntax and library, while considering the migration to Python 3.0, some Python 3.0 syntax and functions are allowed. There is no warning that Python 2.6 runs normally based on earlier versions of Python. The program can seamlessly migrate to Python 3.0 through a 2to3 Conversion Tool. Python has some useful test modules, including doctext and unitest. Make sure that the application is fully tested before you try to port it to Python3. Make sure that the test scope is as large as possible, and the program runs on Python2.6, the test is passed without any warning.
We recommend that you use the Python 3.0 syntax for the new Python program. Unless Python 3.0 cannot be installed in the running environment or the program itself uses a third-party library that does not support Python 3.0. Third-party libraries that do not currently support Python 3.0 include Twisted, py2exe, and PIL. Most third-party libraries are striving to be compatible with Python 3.0. Even if you cannot use Python 3.0 immediately, you are advised to write a program compatible with Python 3.0 and then run it using Python 2.6 and Python 2.7. Python 2.7 is identified as the last version of Python 2.x. In addition to the Python 2.x syntax, it also supports some Python 3.1 syntax.
The changes are summarized as follows:
01. print () and exec () Functions
In earlier versions of python, print and exec appear as one statement. print "Hello, World! ", To print a statement, in the new version, print () and exec () as a function, so the above write is wrong, should be written as print (" Hello, World! ") For Java programmers, this change should be familiar with. System. out. print (" Hello, World! ");
The Code is as follows:
Old: >>> print "The answer is", 2*2
New: >>> print ("The answer is", 2*2)
Old: >>> print x, # Trailing comma suppresses newline
New: >>> print (x, end = "") # Appends a space instead of a newline
Old: >>> print # Prints a newline
New: >>> print () # You must call the function!
Old: >>> print> sys. stderr, "fatal error"
New: >>> print ("fatal error", file = sys. stderr)
Old: >>> print (x, y) # prints repr (x, y ))
New: >>> print (x, y) # Not the same as print (x, y )!
But in Python 2.6: from _ future _ import print_function
The Code is as follows:
>>> From _ future _ import print_function
>>> Print ('Jerry ', 'sherry', sep = '-')
Jerry-Sherry
The following changes are correct in the new version:
The Code is as follows:
>>> Print ("There are <", 2 ** 32, "> possibilities! ", Sep = "")
There are <4294967296> possibilities!
>>> Fid = open ("log.txt", "")
>>> Print ("log.txt", file = fid)
>>> Print ("Foo", "Bar", sep = "% ")
>>> Foo % Bar
Exec () is also a function. In python 2. x, the following code is OK.
The Code is as follows:
>>> Def foo ():
Exec ('a = 4 ')
Print
>>> Foo ()
4
But it won't work in python 3. x. The NameError: global name 'A' is not defined. Because the variable a is not defined. The reason is that exec () acts as a function and only operates the dictionary returned by the globals () and locals () functions. However, the dictionary returned by the locals () function is actually a copy of the local variable. The value assignment in the exec () function only modifies the copy of the local variable, rather than the local variable itself. A solution is provided below:
The Code is as follows:
>>> Def foo ():
_ Locals = locals ()
Exec ('a = 4', globals (), _ locals)
A = _ locals ['a']
Print ()
>>> Foo ()
4
02. Integer and Division
Int and long are unified as int, int represents any precision integer, remove sys. maxint, because int is already the largest integer. The new version removes the ambiguous division symbol ('/') and returns only floating point numbers. In previous versions, if the parameter is int or long, the following floor is returned for the result after division. If the parameter is float or complex, then an appropriate approximation of the result after division is returned.
The Code is as follows:
Old: >>> 1/2 # The result is 0...
New: >>> 1/2 # The result is 0.5 grounded.
03. input () instead of raw_input ()
Simplified.
The Code is as follows:
Old: >>> question = raw_input ("What is your quest? ")
New: >>> question = input ("What is your quest? ")
04. source file encoding is UTF-8 by default
Python 3 has a lot of improvements in character encoding, one of which is the default source file encoding from ASCII to UTF-8, that is to say in the file header plus a variety of patterns of coding = UTF-8 no longer needed!
The Code is as follows:
# Coding: UTF-8
# Vim: fileencoding = UTF-8
#-*-Coding = UTF-8 -*-
# Vim: set fileencoding = UTF-8
05. String formatting changes
The built-in % operator for formatting strings is too limited. The new version adds format (), which is more flexible than before. % will be gradually eliminated. Here are three simple examples:
The Code is as follows:
>>> "I love {0}, {1}, and {2}". format ("eggs", "bacon", "sausage ")
'I love eggs, bacon, and sausage'
>>> "I love {a}, {B}, and {c}". format (a = "eggs", B = "bacon", c = "sausage ")
'I love eggs, bacon, and sausage'
>>> "I love {0}, {1}, and {param}". format ("eggs", "bacon", param = "sausage ")
'I love eggs, bacon, and sausage'
06. Comparison
Python3 is much stricter in terms of values. In Python2, any two objects can be compared, for example:
The Code is as follows:
Old: >>> 11 <'oracle '# Python 2: True
New: >>> 11 <'oracle '# Python 3, which causes TypeError exceptions.
07. The identifier supports non-ASCII characters
The Code is as follows:
All = all
Class Men:
@ Classmethod
Def includes (cls, ta ):
Return isinstance (ta, cls)
Def play together (people ):
If all (men. Include (ta) for ta in people ):
Print ("they are friends ")
Else:
Print ("they are friends ")
Tom = man ()
Jerry = man ()
Play together ([Tom, Jerry])
>>>
They are keyou.
08. Exception Handling
* The exception class must inherit from BaseException, which is the base class of the exception structure.
* Removed StandardError.
* Throw an Exception: Use raise Exception (args) instead of the original raise Exception, args
* Exception Capture: Use the escape t Exception as identifier instead of the original except T Exception, identifier
* Exception chain ).
* Improved some exception information when windows cannot load the mode, with localized processing.
Example 1: Exception Handling in Python 3
The Code is as follows:
# Bind ValueError to the local ex
Try:
X = float ('blah ')
Failed t ValueError as ex:
Print ("value exception occurred", ex)
# Capture two unused exceptions at the same time
Try:
X = float ('blah ')
Failed T (ValueError, NameError ):
Print ("caught both types of exceptions ")
Example 2: Implicit exception chain in Python 3
The Code is as follows:
Def pide (a, B ):
Try:
Print (a/B)
Failed t Exception as exc:
Def log (exc ):
Fid = open('logfile.txt ') # missing 'W'
Print (exc, file = fid)
Fid. close ()
Log (exc)
Pide (1, 0)
09. dictionary dict
Another major change in Python 3.0 is the deletion of the dict. iterkeys (), dict. itervalues (), and dict. iteritems () methods in the dictionary. Instead: dict. keys (), dict. values (), dict. items (), which are patched to return lightweight container objects similar to a set, rather than a list of keys and values. The advantage is that you can perform the set operation on keys and entries without copying them. Dict. has_key () is also removed.
The Code is as follows:
>>> D = {1: "Food", 2: "Book "}
>>> D. keys (), d. values (), d. items ()
>>> For values in d. items ():
Print (values)
(1, 'food ')
(2, 'book ')
>>> Keys = list (d. items ())
>>> Print (keys)
[(1, 'food'), (2, 'book')]
Old: >>> d. has_key (1)
True
New: >>> 1 in d # The New version determines whether the key is in the dictionary.
True
10. Other changes
* Removed backticks (replaced by repr)
* Removed <> (non-equal sign, use! = Replace)
* As and with become keywords
* True, False, and None are converted into keywords.
* _ Getslice __is removed. Syntax a [I: j] is interpreted as a. _ getitem _ (slice (I, j ))
* Nonlocal declaration. You can use nonlocal to declare an external variable (not a global variable)
* Xrange () is renamed to range (). range () is not a list, but an iterator.
* Rename next () to _ next _ (). The new built-in function next () can call the _ next _ () method of an object.
* Octal characters, binary and bin () functions. We should write 0o666 instead of 0666, And the oct () function also made a response change. Similarly, 0b1010 is equivalent to 10. bin (10) returns "0b1010 ″.
The Code is as follows:
>>> 0o13 # convert octal to decimal
11
>>> 0b010101 # convert octal to binary
21