Home > Backend Development > Python Tutorial > Explain the difference between python2 and 3

Explain the difference between python2 and 3

coldplay.xixi
Release: 2021-01-11 09:28:48
forward
3247 people have browsed it

Explain the difference between python2 and 3

Related free learning recommendations: python video tutorial

##The difference between python2 and python3

    The difference
  • 1. Some changes in python3.0
  • ##1.print Function
    • 2.Unicode
    • 3.Division operation
    • 4.Exception
    • 5.xrange
    • 6.Octal literal representation
    • 7. Inequality operator
    • 8. Removed repr expression"
    • 9. Multiple modules were renamed (according to PEP8)
    • 10 .Data type
    Summary

Difference

Python version 3.0, often called python3000, referred to as py3k. Compared with earlier versions of python, this is a major upgrade. In order not to bring too much cumbersomeness, python3.0 was not designed with downward compatibility in mind.

  Many designs for early python versions None of the programs can be executed normally on python3.0. In order to take care of existing programs, python2.6, as a transitional version, basically uses the syntax and libraries of python2.x, while considering the migration to python3.0, allowing the use of some The syntax and functions of python3.0.

 It is recommended that new python programs use the syntax of the python3.0 version. Unless the execution environment cannot install python3.0 or the program itself uses a third-party library that does not support python3.0. It is not currently supported Third-party libraries for python include Twisted, py2exe, PIL, etc.
Most third-party libraries are working hard to be compatible with the python3.0 version. Even if python3.0 cannot be used immediately, it is recommended to write a compatible version 3.0 python program. Then use 2.6 and 2.7 to execute.


1. Some changes in python3.0

1.print function

  The print statement is gone, replaced by the print() function. python2.6 and python2.7 partially support this form of print syntax. In python2.6 and 2.7, the following three forms are equivalent

print "我是菜鸟"print (我是菜鸟) #注意print后边有个空格print("我是菜鸟") #print()不能带有其他任何参数
Copy after login

  However, python2.6 actually supports the new print() syntax

from _future_import print_functionprint("我是个菜鸟","我好菜啊",sep=', ')
Copy after login

2.Unicode

  python2 has ASCII str() type, unicode () is separate and not of byte type. Now python3 has Unicode (utf-8) strings, and a byte class: byte and bytearrays. Since the Python3. The language has some advanced and somewhat complex rules. Division in Python has two operators / and //.

Let’s talk about division first. Python2. result.

  Division in python3.x no longer does this, and the result of division between integers will also be a floating point number. (It can be understood as 0/1 here)

 As for //division, this division is called floor division, and a floor operation will be automatically performed on the result of the division, which is consistent in python2.x and 3.x.

我没女友='I have no girlfriends'print(我没女友)
Copy after login
  Note that the decimal part is not discarded, but the floor operation is performed. If you want to intercept the decimal part, you need to use the trunc function of the math module.

4. Exceptions


Handling exceptions in python3 has also changed slightly. In python3, we use as as the keyword. The syntax for catching exceptions is changed from except exc,var to except exc as var.

 Use the syntax except(exc1,exc2) as var to catch multiple categories of exceptions at the same time. python2.6 already supports these two syntaxes.

·In the 2.x era, all types of objects can be thrown directly. In the 3.x era, only objects that inherit BaseException can be thrown.

·2.x raise statement uses commas to separate the thrown object type and parameters. 3.x cancels this strange writing method and directly calls the constructor to throw the object.

 In the 2.x era, exceptions in the code not only represent program errors, but also often do what ordinary control structures should do. In 3.x, it can be seen that the designers have made exceptions more specific, only Exception catching statements can only be used when an error occurs.

5. For example: for loop or list/set/dictionary comprehension.

 This behaves very much like a generator (for example: "lazy evaluation"). But this xrange-iterable is infinite, which means you can traverse infinitely.
  Due to its lazy evaluation, the xrange() function is faster than the range() function if you want to iterate over it multiple times (such as a for loop). Still, it's not recommended to iterate multiple times rather than iterate once, so the generator starts from scratch each time.
  In python3, range() is implemented like xrange(), so that a dedicated xrange() function no longer exists (xrange() in python3 will throw a named exception.

6. Octal literal representation

  八进制必须写成0o777,原来的形式0777不能用了;二进制0b111。新增了一个bin()函数用于将一个整数转换成二进制字串。python2.6已经支持这两种语法

7.不等运算符

python2.x中不等于 !=和<>
python3.x中不等于只有!=

8.去掉了repr表达式"

python2.x中反引号"相当于repr函数的作用
python3.x中去掉了"这种写法,只允许repr函数,感觉repr只有debug的时候才用,多数时候还是用str函数来用字符串描述对象。

9.多个模块被改名(根据PEP8)

旧名字新名字
_winregwinreg
ConfigParserconfigparser
copy_regcopyreg
Queuequeue
SocketServersocketserver
reprreprlib

  StringIO模块现在被合并到新的io模组内new,md5,gopherlib等模块被删除 。python2.6已经支援新的io模组。
  httplibBase,HTTPServer,CGIHTTPServer,SimpleHTTPServer,Cookie,cookerlib被合并到http包内。取消了exec语句只剩下exec()函数。python2.6已经支援exec()函数。

10.数据类型

  python3.x去除了long类型,现在只有一种整型——int
  新增了bytes类型,对应于2.x版本的八位串,定义一个butes字面量方法如下

b=b&#39;lalala&#39;type(b)#输出<type &#39;bytes&#39;>
Copy after login

str对象和bytes对象可以使用encode()(str->bytes)or.decode()(bytes->str)方法互相转换。

s=b.decode()b1=s.encode()
Copy after login

dict的.keys()、.items和.values()方法返回迭代器,而之前的iterkeys()等函数都被遗弃。同事去掉的还有dict.has_key(),用in替代它吧>_<。


总结

  总之一句话,用python3吧,不要再倔强了!
  才开始学习计算机不久,第一次写博客,如果有问题希望大家指正,希望我们能一起学习一起进步。共勉!

The above is the detailed content of Explain the difference between python2 and 3. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template