What are the main differences between Python 2 and Python 3 (one)

Source: Internet
Author: User

Guido (the father of Python, the Benevolent dictator), during the design of Python3, was affected by an article "Python warts" and decided not to be backwards compatible, otherwise it could not fix most of the defects. ---excerpt from "Fluent Python"

You may never have heard of the tangle of Java learning JDK6 or JDK7, also did not hear that the study of PHP is learning PHP5 or PHP7, but in the Python community, there is such a strange question: "Learn python in the end is learning 2 or learning 3?" "This problem is like menstruation every partition time appears in front of you, also became a lot of beginner's choice puzzled, this question" the initiator "of course is Python its father, everybody is divergent opinions, has said Python2 is the mainstream, the big company all is in use, you should study 2. It is also said that Python3 is the mainstream of the future, most of the third-party framework has basically supported Python3. Personal opinion is that Python2 will still exist for a long time (as long as those with Python2 companies have not closed, will always exist), you go to find a job is likely to need to use 2, and Python3 is also you have to master, because more and more people will move to 3 up, in essence, They are the same language, only a very small part (1%?). There is no strict statistics) incompatible places, so there is no so-called learning which one good, learned one, the other spends little time to master. Today we will introduce some major differences between Python2 and Python3.

Print

One of the most used statements in program debugging might be print that in Python 2, print is a statement, and Python3 is a function. Some people may have doubts, I also see in the Python2 when the function uses:

# py2print("hello")  # 等价 print  ("hello")#py3print("hello")

However, what you see is the appearance, so what is the difference between the two expressions above? The output is the same, but essentially, the former is ("hello") treated as a whole, and the latter print() is a function that receives the string as a parameter.

# py2>>> print("hello", "world")(‘hello‘, ‘world‘)# py3>>> print("hello", "world")hello world

This example is more obvious, in Py2, the print statement is followed by a tuple object, and in Py3, the print function can receive multiple positional parameters. If you want to use print as a function in Python2, you can import print_function in the future module

# py2>>> print("hello", "world")(‘hello‘, ‘world‘)>>> >>> from __future__ import print_function>>> print("hello", "world")hello world
Coding

The default encoding for Python2 is ASSCII, which is one of the reasons why the encoding problem is often encountered in Python2, and why ASSCII is used as the default encoding because the Python language does not appear Unicode. Python 3 defaults to UTF-8 as the default encoding, so you no longer have to write at the top of the file # coding=utf-8 .

# py2>>> sys.getdefaultencoding()‘ascii‘# py3>>> sys.getdefaultencoding()‘utf-8‘

Many articles on the web said that by modifying the default encoding format to solve Python2 coding problem, in fact, this is a big hole, do not do so.

String

The string is one of the biggest changes that makes the coding problem a minimal possibility. In Python2, there are two types of strings, one is Unicode, one is STR, the former represents a text string, the latter represents a sequence of bytes, but there is no obvious boundary between the two, the developer is confused and does not understand the reason for the coding error, but in Python3 the two are strictly differentiated, The string is denoted by str, byte denotes a sequence of bytes, and any data that needs to be written to or transmitted by the network receives only a sequence of bytes, which prevents the problem of coding errors from the source.

Py2 Py3 Performance Conversion function
Str Byte Bytes Encode Storage, transport
Unicode Str Character Decode Show
True and False

True and False are two global variables (first names) in Python2, corresponding to 1 and 0 on numeric values, and since they are variables, they can point to other objects, such as:

# py2>>> True = False>>> TrueFalse>>> True is FalseTrue>>> False = "x">>> False‘x‘>>> if False:...     print("?")... ?

Obviously, the above code violates the design philosophy of Python Explicit is better than implicit. While Python3 corrects this flaw, True and False become two keywords, which always point to two fixed objects and are not allowed to be re-assigned again.

# py3>>> True = 1  File "<stdin>", line 1SyntaxError: can‘t assign to keyword
Iterators

Many of the built-in functions and methods in Python2 return list objects in Python 3 have been changed to return objects similar to iterators, because the lazy loading of iterators makes it more efficient to manipulate big data. The range and xrange functions in Python2 are combined into range, if they are compatible with both 2 and 3:

try:    range = xrangeexcept:    pass

In addition, the Dict.keys (), Dict.values () method of the Dictionary object no longer returns a list, but rather is returned as a "view" object that resembles an iterator. The higher-order functions map, filter, and zip return are not list objects either. The Python2 iterator must implement the next method, and Python3 changes to a__next__

Nonlocal

We all know that in Python2 you can global declare a variable as a global variable in a function, but in a nested function it is impossible to declare a variable as a non-local variable, and in Pyhon3, a new keyword is added nonlcoal to make the non-local variable possible.

def func():    c = 1    def foo():        c = 12    foo()    print(c)func()    #1

Can compare the output of the above two pieces of code

def func():    c = 1    def foo():        nonlocal c        c = 12    foo()    print(c)func()   # 12

In fact, many built-in modules have also made a lot of adjustments, Python3 in the module organization clearer, more advanced class, but also introduced the asynchronous IO, this time to write so much, next time continue.

This article starts with the public number: the Zen of Python

What are the main differences between Python 2 and Python 3 (one)

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.