The difference between python2.x and python3.x

Source: Internet
Author: User
Tags floor division integer division
Python's 3.0 version, 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 in too much of a burden, Python 3.0 did not consider downward compatibility when designing.

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 Python version 3.0 syntax.

Unless the execution environment cannot install Python 3.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来.

1. Performance

PY3.0 runs Pystone benchmark slower than Py2.5 by 30%. Guido that Py3.0 has great space for optimization, and can be used in string and shaping operations.
To achieve a good result of optimization.

Py3.1 performance is 15% slower than Py2.5, and there's a lot of room for improvement.

2. Encoding

py3.x source files use utf-8 encoding by default, which makes the following code legal:
>>> Chinese = ' China '
>>>print (China)
China

3. Syntax

1) removal of <>, all use! =
2) Remove ', all switch to REPR ()
3) keywords join as and with, and True,false,none
4) integer division return floating-point number, to get the integer result, use//
5) Add the nonlocal statement. Use noclocal x to assign a peripheral (non-global) variable directly
6) Remove the print statement and add the print () function to achieve the same functionality. The same EXEC statement has been changed to the EXEC () function

For example:

2.x:print "The answer is", 2*2
3.x:print ("The answer is", 2*2)
2.x:print X, # Stop line wrapping with a comma end
3.x:print (X, end= "") # Use a space instead of a newline
2.x:print # Output New Line
3.x:print () # Output New Line
2.x:print >>sys.stderr, "Fatal error"
3.x:print ("Fatal error", File=sys.stderr)
2.x:print (x, y) # output repr ((x, y))
3.x:print ((x, y)) # is different from print (x y)!
7) Change the behavior of the order operator, e.g. X
8) Input function changed, delete raw_input, use input instead:
2.x:guess = Int (raw_input (' Enter an integer: ') # Method for reading keyboard input
3.x:guess = Int (input (' Enter an Integer: ')) 9) Removes the tuple parameter unpacking. Cannot def (A, (b, c)):p the definition of a function like the
10) The new 8 binary character variable, the OCT () function is modified accordingly.

The 2.X approach is as follows:

>>> 0666
438
>>> Oct (438)
' 0666 '

3.X this:

>>> 0666
Syntaxerror:invalid token ( , line 1)
>>> 0o666
438
>>> Oct (438)
' 0o666 '

11) Added 2 binary literals and bin () functions

>>> Bin (438)
' 0b110110110 '
>>> _438 = ' 0b110110110 '
>>> _438
' 0b110110110 '

12) An extensible iterative solution package. In py3.x, A, b, *rest = seq and *rest, a = seq is legal and requires only two points: rest is a list
The object and the SEQ are iterative.

13) New super (), can no longer give super () parameters,

>>> class C (object):
def __init__ (Self, a):
Print (' C ', a)
>>> class D (C):
def __init (Self, a):
Super (). __init__ (a) # no parameter call super ()
>>> D (8)
C 8
<__main__. D Object at 0x00d7ed90>

14) New Metaclass syntax:

Class Foo (*bases, **kwds):
Pass

15) Support class decorator. Usage is the same as function decorator:

>>> def foo (cls_a):
def print_func (self):
Print (' Hello, world! ')
Cls_a.print = Print_func
Return cls_a
>>> @foo
Class C (object):
Pass
>>> C (). Print ()
Hello, world!.

Class decorator can be used to play civet cats for the great tricks of the prince. See Pep 3129 for more

4. Strings and Byte strings

1) Now the string is only one type of STR, but it is almost the same as the 2.x version of Unicode. 2) for the byte string, refer to the 2nd item in the data type

5. 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)

str objects and Bytes objects can be converted using the. encode () (str-bytes) or. Decode () (bytes-str) methods.

>>> 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. And it's also removed.
Dict.has_key (), replace it with in.

6. Object-oriented

1) Introduce abstract base class (Abstraact base Classes,abcs).
2) the container class and the iterator class are ABCs, so the type in the Cellections module is much more than the Py2.5.

>>> Import Collections
>>> print (' \ n '. Join (DIR (collections)))
Callable
Container
Hashable
Itemsview
Iterable
Iterator
Keysview
Mapping
Mappingview
Mutablemapping
Mutablesequence
Mutableset
Namedtuple
Sequence
Set
Sized

Valuesview
__all__
__builtins__
__doc__
__file__
__name__
_abcoll
_itemgetter
_sys
Defaultdict
Deque

In addition, numeric types are also ABCs. For these two points, see Pep 3119 and Pep 3141.

3) The next () method of the iterator is renamed __NEXT__ () and adds the built-in function next () to invoke the __next__ () method of the iterator
4) added @abstractmethod and @abstractproperty two decorator, writing abstract methods (attributes) more convenient.

7. Exceptions

1) So exceptions are inherited from Baseexception and deleted Stardarderror
2) removed the sequence behavior of the exception class and the. Message property
3) Replace raise Exception with raise Exception (args), args syntax
4) Catch exception syntax change, introduce the AS keyword to identify the exception instance, in Py2.5:

>>> Try:
... raise Notimplementederror (' Error ')
... except Notimplementederror, error: ... print error.message
...
Error
In the Py3.0:
>>> Try:
Raise Notimplementederror (' Error ')
Except Notimplementederror as error: #注意这个 as
Print (str (error))
Error

5) exception chain, because __CONTEXT__ is not implemented in the 3.0A1 version

8. Module changes

1) Remove the Cpickle module, you can use the Pickle module instead. Eventually we will have a transparent and efficient module.
2) removed Imageop module
3) removed Audiodev, Bastion, bsddb185, exceptions, Linuxaudiodev, MD5, Mimewriter, Mimify, Popen2,
Rexec, sets, Sha, Stringold, Strop, Sunaudiodev, timing and Xmllib modules
4) removed BSDDB module (released separately, can be obtained from http://www.jcea.es/programacion/pybsddb.htm)
5) removed new module
6) the Os.tmpnam () and Os.tmpfile () functions are moved to the Tmpfile module
7) Tokenize module now works with bytes. The main entry point is no longer generate_tokens, but Tokenize.tokenize ()

9. Other

1) xrange () renamed to Range (), to get a list using range (), you must explicitly call:
>>> List (range (10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

2) Bytes object can not hash, also does not support B.lower (), B.strip () and B.split () method, but for the latter two may use B.strip (b ' \n\t\r \f ') and b.split (b ') to achieve the same purpose

3) both zip (), map (), and filter () return iterators. and apply (), callable (), coerce (), execfile (), reduce (), and reload
() function is removed now you can use HASATTR () to replace callable (). Hasattr () syntax such as: hasattr (String, ' __name__ ')

4) String.letters and related. Lowercase and. Uppercase are removed, use string.ascii_letters, etc.

5) If x < y cannot be compared, throw an TypeError exception. The 2.x version returns a pseudo-random Boolean value

6) __GETSLICE__ series members were discarded. A[I:J] is converted from context to a.__getitem__ (slice (i, j)) or __setitem__ and
__DELITEM__ Call

7) The file class is discarded in Py2.5:

>>> file

In the py3.x:

>>> file
Traceback (most recent):
File " ", line 1, in
File
Nameerror:name ' file ' is not defined

The difference between python2.x and python3.x in 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/2
0
>>> 1.0/2.0
0.5

Python 3.x:

>>> 1/2
0.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

The above content to introduce to you the difference between python2.x and python3.x, hope to help you.

  • Related Article

    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.