differences between p>
Python2.x and 3.x versions
the 3. version of python is often called Python 3, or Py3k for short. Compared with earlier versions of Python, this is a big upgrade.
in order not to bring too much burden, Python 3. was not designed with backward compatibility in mind.
many programs designed for early Python versions can't run normally on Python 3..
In order to take care of the existing programs, Python 2.6, as a transitional version, basically uses the syntax and library of Python 2.x, and at the same time, it considers the migration to Python 3., allowing some syntax and functions of Python 3. to be used.
the new Python program recommends using the syntax of python version 3..
unless the execution environment cannot install Python 3. or the program itself uses a third-party library that does not support Python 3.. At present, the third-party libraries that do not support Python 3. include Twisted, py2exe, PIL, etc.
most third-party libraries are working hard to be compatible with python version 3.. Even if Python 3. cannot be used immediately, it is recommended to write a program compatible with Python 3., and then use Python 2.6, Python 2.7 to execute it.
Python 3. has changed mainly in the following aspects:
print function
the print statement is gone, and it is 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 there is a space after print("fish") #print () cannot take any other parameters
However, Python 2.6 has actually supported the new print () syntax:
from _ _ future _ _ importprint _ function print ("fish", "panda", sep =',')
unicode
Python 2 has ASCII str () type, and Unicode () is separate, not byte type.
now, in Python 3, we finally have Unicode (utf-8) strings and a byte class: byte and bytearrays.
since Python3.X source files use utf-8 encoding by default, this makes the following code legal:
> > > China = 'china'> > > Print (China) china
Python 2.x
> > > Str = "I love Tiananmen Square in Beijing" > > > Str 'me? Beijing? ¤? Ané? ¨'> > > Str = u "I love Tiananmen Square in Beijing" > > > Stru' I love Tiananmen Square in Beijing'
Python 3.x
> > > Str = "I love Tiananmen Square in Beijing" > > > Str' I love Tiananmen Square in Beijing'
Division operation
Division in p>Python is very high-end compared with other languages, and has a set of complicated rules. There are two operators for division in Python,/and //
First of all,/division:
In python 2.x,/division is similar to most languages we are familiar with, such as Java, C, and the result of integer division is an integer. Ignore the decimal part completely, and floating-point division will keep the decimal part to get a floating-point result.
In python 3.x,/division is no longer done. For division between integers, the result will also be floating-point numbers.
Python 2.x:
> > > 1 / 2> > > 1. / 2..5
Python 3.x:
> > > 1/2.5
For//division, this division is called floor division, which will automatically perform a floor operation on the result of division, 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 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 math module
python 3.x:
> > > import math> > > math.trunc(1 / 2)> > > Math.trunc(-1/2)
exception
The handling of exceptions has also changed slightly in Python 3, where we now use as as a keyword.
the syntax for catching exceptions is defined by? except exc, var? Change to? except exc as var。
using the syntax except (exc1, exc2) as var, you can catch multiple types of exceptions at the same time. Python 2.6 already supports these two grammars.
1. In the era of 2.x, all types of objects can be thrown directly; in the era of 3.x, only objects inherited from BaseException can be thrown.
2. 2.x raise statement uses commas to separate thrown object types from parameters. 3.x cancels this wonderful writing, and just calls the constructor to throw the object directly.
In the era of 2.x, in addition to indicating program errors, exceptions often do things that ordinary control structures should do. In 3.x, we can see that designers make exceptions more specific, and only when errors occur can they be handled by exception capture statements.
xrange
The usage of xrange () to create iterative objects is very popular in Python 2. For example, a for loop or a list/set/dictionary derivation.
this behavior is very similar to that of a generator (for example. "lazy evaluation"). But this xrange-iterable is infinite, which means you can traverse it indefinitely.
because of its lazy evaluation, if you have to traverse it only once, the xrange () function is faster than the range () (such as a for loop). Nevertheless, it is not recommended that you iterate many times compared with one iteration, because the generator starts from scratch every time.
in Python 3, range () is implemented like xrange () so that a special xrange () function no longer exists (xrange () throws a named exception in Python 3). import timeitn = 1def test_range(n):return for i in range(n):passdef test_xrange(n):for i in xrange(n):pass
Python 2print 'Python', python_version()print ' timing range()'%timeit test_range(n)print ' timing xrange()'%timeit test_xrange(n)Python 2.7.6timing range()1 loops, best of 3: 433 ? s per looptiming xrange()1 loops, best of 3: 35 ? s per loop
Python 3print('Python', python_version())print(' timing range()')%timeit test_range(n)Python 3.4.1timing range()1 loops, best of 3: 52 ? s per loop
print(xrange(1))---------------------------------------------------------------------------NameError Traceback (most recent call last)< ipython-input-5-5d8f9b79ea7> in < module> ()----> 1 print (xrange (1)) name error: name' xrange' is not defined
Octal literal quantity means
Octal number must be written as o777, and the original form 777 cannot be used; Binary must be written as b111.
a bin () function has been added to convert an integer into a binary string. Python 2.6 already supports these two grammars.
in Python 3.x, there is only one way to express octal literals, which is o1.
python 2.x> > > o1512> > > 1512
python 3.x> > > 1File "< stdin>" , line 11^SyntaxError: invalid token> > > o1512
inequality operator
Python 2.x does not mean that there are two ways to write! = and <; >
Python 3.x has removed <; > Only! = a way of writing, fortunately, I have never used <; > The habit of
removing the back quotation mark in the repr expression ``
Python 2.x is equivalent to the function of the repr function
In p>Python 3.x, the writing method of ``` has been removed, and only the repr function is allowed. Is the purpose of doing this to make the code look clearer? However, I feel that there are few opportunities to use repr. Generally, it is only used when debugging. Most of the time, str function is used to describe objects with strings. def sendMail(from_: str, to: str, title: str, body: str) -> Bool:pass
Several modules have been renamed (according to PEP8)
Old name
New name
_ winreg winreg
Config parser config parser
copy _ reg copyreg
Queue
Socke. T server socket server
repr reprlib
stringio module is now merged into the new io module. New, md5, gopherlib and other modules have been deleted. Python 2.6 already supports new io modules.
httplib, base httpserver, CGI httpserver, simple httpserver, cookie and cookie lib are merged into the http package.
the exec statement is cancelled, leaving only the exec () function. Python 2.6 already supports the exec () function.
5. data type
1)Py3.X removes the long type, and now there is only one integer-int, but its behavior is like the 2.X version of long
2) bytes type is added, which corresponds to the 2.X version of octet string. The method of defining a byte literal is as follows: > > > b = b'china'> > > type(b)< type 'bytes'>
str objects and bytes objects can use. encode() (str -> >; bytes) or .decode() (bytes -> Str) methods are transformed into each other. > > > s = b.decode()> > > s'china'> > > b1 = s.encode()> > > B1b'china'
3)dict's. keys (),. items and. values () methods return iterators, while previous functions such as iterkeys () are discarded. At the same time, dict.has_key () is removed, so replace it with in.