Python 3.x new features and 10 big changes

Source: Internet
Author: User
Tags throw exception
The Python 3.x starting version is Python 3.0, and the latest version is 3.3.3

Guido van Rossum, the father of Python, talked about the idea of Python 3.0:

Until backward compatibility is broken, many flaws and errors cannot be repaired. As a result, Python 3000 will be the first Python version to discard backwards compatibility, in order to get Python moving in the best possible language.

The 3.0 version of Python, often referred to as Python 3000, or simply py3k. This is a large upgrade relative to earlier versions of Python. In order not to take too much of a burden, Python 3.0 did not consider backwards compatibility when designing. Many programs designed for early Python versions do not work correctly 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. No warning is available for Python 2.6 based on earlier Python versions. The program can be migrated seamlessly to Python 3.0 via a 2TO3 conversion tool. Python has some very useful test modules, including DocText and Unitest. Ensure that the application is thoroughly tested before attempting to migrate to Python3. To ensure that the test scope is as large as possible, and that the program runs on Python2.6, it can pass the test and no warning message appears.

The new Python program recommends using the Python version 3.0 syntax. Unless the running environment cannot install Python 3.0 or the program itself uses a third-party library that does not support Python 3.0. Third-party libraries that currently do not support Python 3.0 are 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 run it using Python 2.6, Python 2.7来. Python 2.7 was identified as the last Python 2.x version, which supports some Python 3.1 syntax in addition to the Python 2.x syntax.


The changes are broadly summarized as follows:

01.print () and EXEC () functions

In the old Python version, print and exec appear as a statement and can print a statement with print "hello,world!", and in the new version, print () and exec () appear as a function, so the above write is wrong, should be written as print ("hello,world!") For Java programmers, such a change should be more familiar. System.out.print ("hello,world!");
Copy the Code code 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 () # 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)!


However, in Python version 2.6: from __future__ import print_function
Copy CodeThe code is as follows:


>>> from __future__ import print_function
>>> print (' Jerry ', ' Sherry ', sep= '-')
Jerry-sherry


The following modifications are correct in the new version:
Copy CodeThe code is as follows:


>>>print ("There is <", 2**32, "> possibilities!", sep= "")
There is <4294967296> possibilities!
>>>fid = open ("Log.txt", "a")
>>>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.
Copy the Code code as follows:


>>> def foo ():
EXEC (' a=4 ')
Print a
>>> foo ()
4


But not in Python 3.x, it will be reported Nameerror:global name ' A ' is not defined. Because variable a is not defined. The reason is that exec () acts as a function, manipulating only the dictionaries returned by the Globals () and locals () functions. But the dictionary returned by the locals () function is actually a copy of the local variable. The assignment in the EXEC () function modifies only the copy of the local variable, not the local variable itself. Here's a workaround:
Copy CodeThe code is as follows:


>>> def foo ():
_locals = locals ()
EXEC (' a=4 ', Globals (), _locals)
A = _locals[' a ']
Print (a)
>>> foo ()
4

02. Integers and divisions

int and long are uniformly int, int represents any integer of precision, and sys.maxint is removed because int is already the largest integer. The new version removes the ambiguous Division symbol ('/') and returns only the floating-point number. In previous versions, if the argument was an int or a long, it would return a downward rounding (floor) of the result after division, and if the parameter was float or complex, a proper approximation of the result would be returned.
Copy the Code code as follows:


Old: >>>1/2 #结果是0 Dizzy dead ...
New: &GT;&GT;&GT;1/2 #结果是0.5 finally grounded the gas.


03.input () instead of raw_input ()
It has become concise.
Copy CodeThe code is as follows:


Old: >>>question = Raw_input ("What's Your Quest?")
New: >>>question = input ("What's Your Quest?")

04. source file encoding defaults to UTF-8
Python 3 has many improvements in character encoding, one of which is that the default source file encoding is changed from ASCII to UTF-8, which means that the coding=utf-8 of the various tricks that were added to the file header are no longer needed!
Copy the Code code as follows:


# Coding:utf-8
# Vim:fileencoding=utf-8
#-*-Coding=utf-8-*-
# Vim:set Fileencoding=utf-8

05. String Formatting changes
This built-in% operator of the formatted string is too limited, and the new version adds format (), which is more flexible than before and is gradually obsolete. Give three simple examples as follows:
Copy the Code code 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. Compare
Python3 is much more rigorous about values. In Python2, any two objects can be compared, for example:
Copy CodeThe code is as follows:


Old: >>>11 < ' ORACLE ' # Python 2 result is: True
New: >>>11 < ' ORACLE ' # Python 3 This comparison will result in TypeError exceptions

07. Identifiers Support Non-ASCII characters
Copy the Code code as follows:


all = All
Class Man:
@classmethod
def includes (Cls,ta):
Return Isinstance (TA,CLS)
Def play with (people):
If all (men. including (TA) for TA in people):
Print ("They are the base friends")
Else
Print ("They are friends")
Tom = Man ()
Jerry = Man ()


Play Together ([Tom, Jerry])

>>>
They're friends.

08. Exception Handling
* The exception class must inherit from Baseexception, which is the base class for the exception structure.
* Removed StandardError
* Throw exception: Use raise Exception (args) instead of the original raise Exception, args
* Catch exception: use except Exception as identifier instead of original except Exception, identifier
* Abnormal chain (Exception chain).
* Improved some exception information when Windows cannot load the schema, with native processing.
Example exception handling in 1:python 3
Copy the Code code as follows:


# bind ValueError to local ex
Try
x = float (' blah ')
Except ValueError as ex:
Print ("Value exception occurred", ex)

# Capture two unused exceptions at the same time
Try
x = float (' blah ')
Except (ValueError, Nameerror):
Print ("Caught both types of exceptions")


Example of an implicit exception chain in 2:python 3
Copy CodeThe code is as follows:


Def divide (A, B):
Try
Print (A/b)
Except Exception as exc:
def log (exc):
FID = open (' LogFile.txt ') # missing ' W '
Print (exc, file=fid)
Fid.close ()
Log (EXC)


Divide (1,0)

09. Dictionary Dict

Another significant change within Python 3.0 is the deletion of the dictionary within the Dict.iterkeys (), Dict.itervalues (), Dict.iteritems () method. Instead, Dict.keys (), Dict.values (), Dict.items (), which are patched, can return a lightweight, set-like container object instead of a list of keys and values. The benefit is that you can perform a set operation on a key and an item without copying it. Dict.has_key () is also removed.
Copy the Code code 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 #新版本判断key是否在字典里面
True

10. Other changes

* Remove Backticks (use REPR () instead)
* Remove <> (not equal, use! = instead)
* As and with have become keywords
* True,false and none have become keywords
* Removed __getslice__, grammar a[i:j] interpreted as a.__getitem__ (Slice (i,j))
* nonlocal statement. Use nonlocal to declare an external variable (not a global variable)
* Xrange () renamed to Range (), range () is now not a list, but an iterator.
* Next () renamed to __next__ (), the new built-in function next () can call an object's __next__ () method.
* octal characters, binary and bin () functions. The 0o666 instead of the 0666,oct () function should be written in response to the change. Similarly, 0b1010 is equivalent to 10,bin (10) returning "0b1010″.
Copy the Code code as follows:


>>>0o13 #八进制转十进制
11
>>>0b010101 #八进制转二进制
21st
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.