The difference between python2.x and 3.x

Source: Internet
Author: User

3??. of Python Version 0, 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来.

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. Python 2.6 and Python 2.7 support this form of print syntax in parts. In Python 2.6 and Python 2.7, the following three forms are equivalent:

print "Fish"

Print ("Fish") #注意print后面有个空格

Print ("Fish") #print () cannot have any other parameters

However, Python 2.6 has actually supported the new print () syntax:

From __future__ import print_function

Print ("Fish", "Panda", sep= ', ')

Unicode

Python 2 has an ASCII str () type, Unicode () is separate, not a byte type.

Now, in Python 3, 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:

>>> Chinese = ' China '

>>>print (China)

China

Python 2.x

>>> str = "I love Beijing Tian ' an men"

>>> 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 Beijing Tian ' an men"

>>> Str

U ' \u6211\u7231\u5317\u4eac\u5929\u5b89\u95e8 '

Python 3.x

>>> str = "I love Beijing Tian ' an men"

>>> Str

I love Beijing Tian ' an door

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

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.

1. 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.

2.2.x raise statement using commas to throw object types and parameters separated, 3.x canceled the work of this kind of flower, directly call the constructor to throw objects.

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

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

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 ()

Loops, Best of 3:433µs per loop

Timing Xrange ()

Loops, Best of 3:350µs per loop

Python 3

Print (' Python ', Python_version ())

Print (' \ntiming range () ')

%timeit Test_range (N)

Python 3.4.1

Timing Range ()

Loops, Best of 3:520µs per loop

Print (Xrange (10))

---------------------------------------------------------------------------

Nameerror Traceback (most recent)

<ipython-input-5-5d8f9b79ea70> in <module> ()

----> 1 Print (xrange (10))

Nameerror:name ' xrange ' is not defined

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

>>> 0o1000

512

>>> 01000

512

Python 3.x

>>> 01000

File "<stdin>", line 1

01000

^

Syntaxerror:invalid token

>>> 0o1000

512

Inequality operator

Python 2.x does not equal two ways!! = and <>

Python 3.x removed the <> only! = a kind of notation, fortunately, I never used <> habits

Removed the repr expression '

The inverse quotation mark in Python 2.x is equivalent to the effect of the REPR function

Python 3.x has removed the notation, allowing only the REPR function to be used to make the code look clearer? However, I feel that the opportunity to use repr is very rare, usually only used when debugging, and most of the time, the STR function is used to describe the object with a string.

def sendMail (from_: str, TO:STR, TITLE:STR, BODY:STR), BOOL:

Pass

Multiple modules are renamed (according to PEP8)

The old name, the 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. Python 2.6 already supports the EXEC () function.

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)

<type ' bytes ' >

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. Also remove the Dict.has_key (), with in instead of it.

The difference between python2.x and 3.x

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.