Let's talk about the differences between Python2.x and 3.x, namely, python2.x. x.

Source: Internet
Author: User

Let's talk about the differences between Python2.x and 3.x, namely, python2.x. x.

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 burden into it, Python 3.0 does not consider backward compatibility during design.

Many programs designed for earlier versions of Python cannot be normally executed 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.

We recommend that you use the Python 3.0 syntax for the new Python program.

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. Third-party libraries that do not 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 3.0 changes mainly in the following aspects:

Print function

The print statement is missing and replaced by the print () function. Python 2.6 and Python 2.7 partially support this form of print syntax. In Python 2.6 and Python 2.7, the following three forms are equivalent:

Print "fish" print ("fish") # note that print ("fish") is followed by a space. print () cannot contain any other parameter.

However, Python 2.6 actually supports the new print () Syntax:

from __future__ import print_functionprint("fish", "panda", sep=', ')
Unicode

Python 2 has the ASCII str () type, and unicode () is separate, not the byte type.

Now, in Python 3, we finally have a Unicode (UTF-8) string and a byte Class: byte and bytearrays.

Because the Python3.X source code file uses UTF-8 encoding by default, the following code is legal:

>>> China = 'China' >>> print (china) china

Python 2.x

>>> Str = "I love Beijing Tiananmen" >>> 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 Tiananmen Square in Beijing" >>> stru' \ u6211 \ u7231 \ u5317 \ u4eac \ u5929 \ u5b89 \ u95e8'

Python 3.x

>>> Str = "I love Beijing Tiananmen" >>> str 'I love Beijing Tiananmen'
Division

Division in Python is more advanced than other languages and has complicated rules. Division in Python has two operators: // and //

First, Division:

In python 2. division in x is similar to that in most familiar languages, such as Java and C. The result of division of integers is an integer, and the fractional part is completely ignored, the floating point Division retains the decimal point to get a floating point number.

In python 3. x, division is no longer done. For the division between integers, the result will also be a floating point.

Python 2.x:

>>> 1 / 20>>> 1.0 / 2.00.5

Python 3.x:

>>> 1/20.5

For // division, this division is called floor division, which automatically performs a floor operation on the division result, which is consistent in python 2. x and python 3. x.

Python 2.x:

>>> -1 // 2-1

Python 3.x:

>>> -1 // 2-1

Note that the floor operation is not to discard the decimal part, but to intercept the decimal 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
Exception

Processing exceptions in Python 3 are also slightly changed. In Python 3, we now use as a keyword.

Syntax for capturing exceptionsCallback t exc, varChangeUsing t exc as var.

You can use the syntax limit T (exc1, exc2) as var to capture multiple types of exceptions at the same time. Python 2.6 supports these two syntaxes.

  • 1. In the 2. x era, all types of objects can be directly thrown. In the 3. x era, only objects inherited from BaseException can be thrown.
  • 2. The 2.x raise statement uses commas to separate the type of the thrown object from the parameter. 3. x cancels this wonderful writing method and directly calls the constructor to throw the object.

In 2. in the era of x, exceptions not only indicate program errors, but also often do things that should be done by common control structures. x shows that the designer makes exceptions more specific and can use exception capture statements only when errors occur.

Xrange

In Python 2, the use of xrange () to create iterative objects is very popular. For example, for loop or list/set/dictionary derivation.

This is like a generator (for example. "Evaluate inertia "). But this xrange-iterable is infinite, which means you can traverse it infinitely.

Because of its inertia, if you do not just traverse it once, the xrange () function is faster than range () (for example, for loop ). Even so, we do not recommend that you repeat the iteration multiple times because the generator starts from the beginning each time.

In Python 3, range () is implemented like xrange () so that a special xrange () function no longer exists (in Python 3, xrange () throws a naming exception ).

import timeitn = 10000def test_range(n):    return for i in range(n):        passdef 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.6timing range()1000 loops, best of 3: 433 µs per looptiming xrange()1000 loops, best of 3: 350 µs per loop

Python 3

print('Python', python_version())print('\ntiming range()')%timeit test_range(n)Python 3.4.1timing range()1000 loops, best of 3: 520 µs per loopprint(xrange(10))---------------------------------------------------------------------------NameError                                 Traceback (most recent call last)<ipython-input-5-5d8f9b79ea70> in <module>()----> 1 print(xrange(10))NameError: name 'xrange' is not defined
Octal literal representation

The octal number must be written as 0o777. The original format 0777 cannot be used, and the binary value must be written as 0b111.

A bin () function is added to convert an integer to a binary string. Python 2.6 supports these two syntaxes.

In Python 3. x, there is only one way to represent the octal literal, that is, 0o1000.

Python 2.x

>>> 0o1000512>>> 01000512

Python 3.x

>>> 01000  File "<stdin>", line 1    01000        ^SyntaxError: invalid token>>> 0o1000512
Unequal Operators

Python 2.x does not have to be written in two ways! = And <>

Python 3. x is removed <>, only! = A writing method. Fortunately, I have never used it <>

The repr expression ''is removed''

Backquotes ''in Python 2.x are equivalent to the repr function.

Python 3.x removes ''and only supports the repr function. Is this done to make the Code look clearer? However, I feel that there are few opportunities to use repr, which are generally used only during debugging. Most of the time, the str function is used to describe objects using strings.

def sendMail(from_: str, to: str, title: str, body: str) -> bool:    pass
Multiple modules are renamed (according to PEP8)
Old Name New name
_ Winreg Winreg
ConfigParser Configparser
Copy_reg Copyreg
Queue Queue
SocketServer Socketserver
Repr Reprlib

The StringIO module is now merged into the new io module. New, md5, gopherlib, and other modules are deleted. Python 2.6 supports new I/O modules.

Httplib, BaseHTTPServer, CGIHTTPServer, SimpleHTTPServer, Cookie, and cookielib are merged into the http package.

The exec statement is canceled, and only the exec () function is left. Python 2.6 supports the exec () function.

5. Data Type

1) Py3.X removes the long type, and now there is only one integer -- int, But it acts like the long type

2) The bytes type is added, which corresponds to the 8-Bit String Of The 2.x version. The following describes how to define a bytes literal:

>>> b = b'china' >>> type(b) <type 'bytes'>

The str object and bytes object can be converted using the. encode () (str-> bytes) or. decode () (bytes-> str) method.

>>> s = b.decode() >>> s 'china' >>> b1 = s.encode() >>> b1 b'china'

3) dict's. keys (),. items, and. values () Methods return to the iterator, while previous iterkeys () and other functions are discarded. Dict. has_key () is also removed. Replace it with in.

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.