Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Python 2.x is different from the 3 .x version


May 10, 2021 Python2


Table of contents


Python version 3.0, often referred to as Python 3000, or Py3k for short. This is a larger upgrade than earlier versions of Python.

In order not to bring too much burden, Python 3.0 was designed without considering downward compatible.

Many programs designed for earlier versions of Python do not perform properly on Python 3.0.

To take care of existing programs, Python 2.6, as a staging version, basically uses the syntax and libraries of Python 2.x, taking into account the migration to Python 3.0, allowing the use of some of Python 3.0's syntax and functions.

The new Python program recommends python version 3.0 syntax.

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 currently support Python 3.0 have Twisted, py2exe, PIL, etc.

Most third-party libraries are working hard to compatible with Python 3.0 versions. Even if Python 3.0 cannot be used immediately, it is recommended to write a program that is compatible with Python 3.0 and then execute using Python 2.6, Python 2.7.

The change in Python 3.0 is mainly in the following areas:


The print function

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

print "fish"
print ("fish") #注意print后面有个空格
print("fish") #print()不能带有任何其它参数

However, Python 2.6 actually supports the new print()

from __future__ import print_function
print("fish", "panda", sep=', ')

Unicode

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

Now, in Python 3, we finally have Unicode (utf-8) as well as a byte class: bytearrays

Because Python 3.X source files are utf-8 by default, the following code is legal:

>>> 编程狮 = 'W3Cschool' 
>>>print(编程狮) 
W3Cschool

Python 2.x

>>> str = "我爱北京天安门"
>>> str
'\xe6\x88\x91\xe7\x88\xb1\xe5\x8c\x97\xe4\xba\xac\xe5\xa4\xa9\xe5\xae\x89\xe9\x97\xa8'
>>> str = u"我爱北京天安门"
>>> str
u'\u6211\u7231\u5317\u4eac\u5929\u5b89\u95e8'

Python 3.x

>>> str = "编程狮"
>>> str
'编程狮'

Division operations

The method of divide in Python is very high-end compared to other languages, with a complex set of rules. Division in Python has two operators, / //

First of all/ divide:

In python 2.x / divide is similar to most languages we are familiar with, such as Java ah C ah, the result of integers divided is an integer, the part of the number of points is completely ignored, the floating point divide will retain the part of the number of points to get a floating point result.

In python 3.x / divide no longer does this, and for the dithes between integers, the result is floating points.

Python 2.x:

>>> 1 / 2
0
>>> 1.0 / 2.0
0.5

Python 3.x:

>>> 1/2
0.5

For // divide, this divide, called floor divide, automatically performs a floor operation on the result floor the divide, 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 instead of discarding the dicholy part, floor and if you want to intercept the integer part, you need to use the math trunc function

python 3.x:

>>> import math
>>> math.trunc(1 / 2)
0
>>> math.trunc(-1 / 2)
0

Abnormal

Handling exceptions in Python 3 also changed slightly, and in Python 3 we now use as key word.

The syntax for catching except exc var var to except except exc as var

Using the except (exc1, exc2) as var can catch multiple categories of exceptions at the same time. Python 2.6 already supports both syntaxes.

  1. In the 2.x era, all types of objects can be thrown directly, and in the 3.x era, BaseException can be thrown.
  2. The 2.x raise uses a comma to separate the throw object type from the argument, and 3.x eliminates this odd writing and calls the constructor directly to throw the object.

In the 2.x era, exceptions in code in addition to representing program errors, but also often do some ordinary control structure should do things, in 3.x can be seen that the designer makes exceptions become more specific, only in the event of errors can be handled with exception catch statements.


xrange

The use of xrange() Python 2 is very popular. For example: for loops or lists/collections/dictionary inferences.

This behaves very much like a generator (for example. L azy 惰性求值 But this xrange-iterable meaning you can traverse it indefinitely.

Because of its inertness, if you can't just traverse it once, xrange() function range() (for for However, comparing iterations once does not recommend that you repeat iterations multiple times, because the generator starts from scratch each time.

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

import timeit

n = 10000
def test_range(n):
    return for i in range(n):
        pass

def 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.6

timing range()
1000 loops, best of 3: 433 µs per loop


timing 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.1

timing range()
1000 loops, best of 3: 520 µs per loop
print(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 literally

The octal number must be 0o777 the original form 0777 is not useful, and the binary must be 0b111

A bin() added to convert an integer into a binary string. Python 2.6 already supports both syntaxes.

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

python 2.x

>>> 0o1000
512
>>> 01000
512

python 3.x

>>> 01000
  File "<stdin>", line 1
    01000
        ^
SyntaxError: invalid token
>>> 0o1000
512

Inequality operators

Python 2.x does not mean that there <> are two ways to !=

Python 3.x has been removed from <> != <>


Removed the repr expression'

The quotation marks `` in Python 2.x are equivalent to repr function

Did Python 3.x get rid of `` and allow only repr function to make the code look clearer? However, I feel that there are very few opportunities to use repr debug most of the time str to describe objects in strings.

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

Multiple modules have been renamed (according to PEP8)

Old name New name
_winreg winreg
ConfigParser configparser
copy_reg copyreg
Queue queue
SocketServer socketserver
repr reprlib

StringIO module is now merged io module. new md5 , gopherlib are removed. Python 2.6 already supports the io module.

httplib BaseHTTPServer CGIHTTPServer SimpleHTTPServer Cookie cookielib incorporated http package.

The exec canceled, exec() function. Python 2.6 already supports exec() function.


5. Data type

1) Python 3.X removes long type and now has only one integer, long int but it behaves like the long version of Python 2.X

2) bytes corresponding to the Python 2.X version of the eight-bit string, bytes literal method as follows:

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

str bytes can be converted to each other using the .encode() ( str -> bytes ) .decode() ( bytes -> str ) methods.

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

3) dict .keys() .items .values() while iterkeys() are discarded. Also removed is dict.has_key() in it with in.


Related tutorials