[Python Tutorial] Differences between Python2.x and 3.x

Source: Internet
Author: User
Tags integer division
Python 3.0 is often called Python3000 or Py3k. Compared with earlier versions of Python, this is a major upgrade. Python3.0 did not consider backward compatibility during design so as not to bring too much burden into it.

Differences between Python2.x and 3.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.

Major changes

Python 3.0 changes mainly in the following aspects:

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=', ')

The new str category indicates a Unicode string, which is equivalent to the unicode category of Python 2.x. The Bitte sequence is represented by the syntax similar to B "abc" and bytes class, which is equivalent to the str class of Python 2. x.

Currently, the two classes cannot be implicitly automatically converted, so "fish" + B "panda" in Python 3. x is an error. The correct syntax is "fish" + B "panda". decode ("UTF-8 "). Python 2.6 can automatically recognize the sequence of tuples as Unicode strings by using the following methods:

from __future__ import unicode_literalsprint(repr("fish"))

The division operator "/" Always returns a floating point number in Python 3. x. In Python 2.6, the system checks whether the divisor and divisor are integers. If it is an integer, an integer is returned, which is equivalent to the integer division. if it is a floating point, a floating point value is returned.

To allow Python 2.6 to return a floating point value uniformly, you can:

from __future__ import pisionprint(3/2)

The syntax for exception capturing is changed from syntax T exc and var to syntax 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.

New syntax for set: {1, 2, 3, 4 }. Note that {} still indicates an empty Dictionary (dict ).

Dictionary derivation {expr1: expr2 for k, v in d}. this syntax is equivalent

result={}for k, v in d.items():    result[expr1]=expr2return result

Set Comprehensions {expr1 for x in stuff }. This syntax is equivalent:

result = set()for x in stuff:    result.add(expr1)return result

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.

Dict. keys (), dict. values (), dict. items (), map (), filter (), range (), zip () does not return the list, but an iterator.

If no meaningful order is defined between two objects. When you use <,>, <=,> = to compare them, an exception is thrown. For example, 1 <"" returns True in Python 2.6, and an exception is thrown in Python 3.0. Now the cmp () and instance. _ cmp _ () functions have been deleted.

You can annotate the parameters and return values of a function. This feature allows IDE to perform more in-depth analysis on the original code. For example, add a category message to a parameter:

def sendMail(from_: str, to: str, title: str, body: str) -> bool:    pass

Merge int and long types.

Multiple modules are renamed (according to PEP8 ):

Old name

New name

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

The above is the difference between Python2.x and 3.x in the [python Tutorial]. For more information, see The PHP Chinese website (www.php1.cn )!

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.