What are the main differences between Python2 and Python3?

Source: Internet
Author: User
Php Chinese network (www.php.cn) provides the most comprehensive basic tutorial on programming technology, introducing HTML, CSS, Javascript, Python, Java, Ruby, C, PHP, basic knowledge of MySQL and other programming languages. At the same time, this site also provides a large number of online instances, through which you can better learn programming... Reply content: I will correct and comment.
> 1. print is no longer a statement, but a function. for example, print 'ABC' is now print ('ABC ')
However, python2.6 + can use the from _ future _ import print_function to implement the same function.
> 2. in Python 3, there are no old classes and only new classes. that is to say, class Foobar (object): pass explicitly subclass object.
The main difference is that the old-style is of the classtype type while the new-style is of the type.
> 3. the original result of 1/2 (division of two integers) is 0, and now it is 0.5.
For python 2.2 + and later versions, you can use from _ future _ import pision to implement the feature modification. Note that // replaces the previous/operation.
> 4. replace % with the new string formatting method format.
Error. this method has been available in str and unicode since python2.6 +, and python3 still supports the % operator.
> 6. rename xrange to range.
At the same time, a series of built-in functions and methods are modified, which return iterator objects instead of lists or tuples, such as filter, map, dict. items, etc.
> 7 .! = Replace <>
Python2 is rarely used.
> 8. rename long to int.
Not completely correct. python3 completely disused the long + int double integer implementation method, unified as int, supports high-precision integer calculation.
> 9. except T Exception, e becomes except T (Exception) as e
This syntax is not supported only in python2.5 and earlier versions. python2.6 is supported.
> 10. exec is a function.
Similar to the changes in print (), which were previously statements.

Simply add
* The main reason is the changes in the class library. the organizational structure has changed, but the function has not changed. urlparse-> urllib. parse.
* The core change is not mentioned. For bytes and native UNICODE strings, unicode objects are deleted and str is a native unicode string, bytes replaces the previous str, which is the core.
* Others... seem to be not very important. if you don't say anything about it, let me add a very important one:
Import is imported using absolute paths by default in Python3, because the import of relative paths is ambiguous.
For example, the folder structure:
  • Test/
    • Main. py
    • Lib/
      • _ Init _. py
      • Some_func.py
      • Other_func.py
If the main. py file is running, python uses the current cwd as the PYTHONPATH variable.
In main. py
Import lib. some_func
Or
From lib import some_func
In some_func.py, if you use import other_func, an error is returned. we recommend that you use
From lib import other_func
Forcible use of the relative import requires from. other_func import *
Therefore, if you migrate from Python2 to Python3, you will see whether the original code structure of a large project is good. if your code is relatively imported everywhere... Zookeeper
For more details, see PEP 0328 -- Imports: Multi-Line and Absolute/Relative.

For details about 2to3 migration, refer to the documentation of 2to3: 26.6. 2to3-Automated Python 2 to 3 code translation. Manual migration is not required ~ Main differences between Python 2.7.x and Python 3.x , Describes the differences between Python 2 and Python 3 in detail, and posts some good articles in it, hoping to help you. Main differences between Python 2.7.x and Python 3.x
  • Use the _ future _ module
  • Print function
  • Integer pision
  • Unicode
  • Xrange
  • Raising exceptions
  • Handling exceptions
  • Next () function and. next () method
  • For loop variable and global namespace leakage
  • Comparison of non-sorting types
  • Parse user input through input ()
  • Returns the iteratable object instead of the list.

Original address:
Key differences between Python 2.7.x and Python 3.x

The translation address is
Main differences between Python 2.7.x and Python 3.x The main difference between modification is that The Python3 program can be written in Chinese..

But the funny thing is that some people say they are not very familiar with Chinese writing programs (the original words ).

I think he means he is not used to it, but he is still funny. Want to know if he is used to looking in the mirror every day

If there is such a abnormal company/boss, there will be no way to do it. Py3 is more standardized and unified than py2. it doesn't mean py2 is not good, but it is complicated because of historical reasons or problems in design ideas at the beginning.

Print changes remove unnecessary keywords. In other words, functions can be used to solve the problem. lightweight syntax + rich libraries, no special features, exec and! =, <> It is almost based on the same idea (but for exec, there is a problem that needs to be confirmed, as described below)
Int and long are merged, and new and old classes are merged. for the same reason as above, they are unified. Simply put, if A can implement all the functions of B, or B can be simply constructed from, B does not need to exist.
Returned iterators such as range and map are also based on the same reason. to implement the range of py2, you only need list (range (...)), but in turn, to implement the iterator version of py2, only one xrange can be added, instead of directly obtaining from range (range will consume memory)
The character string is changed to unicode for saving, and the addition of byte strings is also to adapt to the Times. This article seems to be praised a lot. However, I still want to say that it is most important to clarify the encoding problem, people who are confused may have problems with anything, but the difference in probability size.

Finally, let's talk about the exec problem, because I don't need py3, I haven't studied it in depth, and people who want to understand it will reply directly, or I have to install a study ..
As a dynamic language, the value of the variable scope of py can be roughly considered to be stored in dict in the form of {variable name: value}. In fact, the global domain is like this, however, some local variables of the function are special. the number of local variables is determined during compilation, so they can be stored in arrays, such
Def f ():
A = 1
B = 2
Print a + B
Here, a and B are not in the form of {a: 1, B: 2}. the internal implementation is an array, which is roughly [1, 2] (of course not a list, in fact, the CPython virtual machine uses a Tuple-like object), and then the access can be directly done with offset, so the execution speed is significantly improved, because the vast majority of the operations of most programs are within the function, this situation is also true in most languages.
But if exec exists, there will be a problem:
Def f ():
A = 1
Exec "B = 2"
Print a + B
In this way, we can dynamically increase or decrease the variables in the local variable domain, and the compiler cannot perceive them. because the string executed by exec may be dynamically generated and cannot be perceived by the compiler, py2's approach to this situation is, if a function contains exec, the access method of the local variable domain of this function is different from that of the normal function. Instead, the access method is in the form of dict similar to the global domain.
So this requires the compiler to perceive whether a function contains exec. Therefore, exec is necessary as a language keyword. if it is used as a function, it may be hard for the compiler to perceive it, because py can assign a function to a variable with another name, or assign a value to the original function name. I think it is more powerful than two points.
  1. Encoding problems
  2. Add async coroutine
RTFM.

This kind of thing can be viewed directly on the official website, and there is no need to raise a question.
Additional link: What's New In Python 3.0 Help upstairs make up some
Google "python 2 3 differences"
Http://goo.gl/vs1ou 1. print is no longer a statement, but a function. for example, print 'ABC' is now print ('ABC ')
2. in Python 3, there are no old classes and only new classes. that is to say, class Foobar (object): pass explicitly subclass object.
3. the original result of 1/2 (division of two integers) is 0, and now it is 0.5.
4. replace % with the new string formatting method format
5. rename raw_input to input.
6. rename xrange to range.
7 .! = Replace <>
8. rename long to int.
9. failed t Exception, e becomes failed t (Exception) as e
10. exec is a function.

There are many others...

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.