Novice Python Learn whether to learn Python2 or Python3__python

Source: Internet
Author: User
Tags integer division

People who want to learn Python have a puzzle, that is, Python currently has two versions of Python2 and Python3,python2 and Python3, what is the difference between two versions should learn which.

Python3 and Python2 are incompatible, and the differences are relatively large, python3 are not backward compatible, but most of the components and extensions are based on Python2. At present, most of the practical applications are not considered Python3, and sometimes pay attention to write compatible with 2/3 of the code. When you write new code with Python2, consider the possibility of migrating to Python3 later. According to statistics, currently 10% uses Python 3;20% to use Python 2 as well as Python 3,python2, and 70% uses Python 2.

In fact, Python is one of the most commonly used software on Linux, but the current version of Linux is mostly used Python2, and, on Linux rely on Python2 program more, so Python3 to replace python2 become mainstream still need a few years time. If you learn Python 2 to find a job or learn Python 2, it's not hard to go from Python 2 to Python3.

Said for a long time, Python2 and Python3 What is the difference?

1. Performance
Py3.0 runs Pystone benchmark faster than Py2.5 30% slower. Guido that Py3.0 has great optimization space, and can achieve good results in string and plastic operation.
Py3.1 performance is 15% slower than Py2.5, and there is a lot of room for improvement.
2. Encoding
The py3.x source file uses Utf-8 encoding by default, which makes the following code legal:
   >>> china = ' Chinese '
   >>>print (China)
   Chinese
3. Syntax
1) removed <>!=
2) Remove ", all use Repr ()
3) keyword to add as and with, and True,false,none
4) integer division return floating-point number, to get the integer result, please join//
5) To add the nonlocal statement. Use noclocal x to directly assign the outer (non-global) variable
6) to remove the print statement and add the print () function to achieve the same functionality. There is also the EXEC statement, which has been changed to exec () function
   For example:
   2.x:print "The answer is", 2*2
   3.x:pri NT ("The answer is", 2*2)
   2.x:print X, # Use the end of commas to prevent line wrapping
   3.x:print (X, end= "") # Use a space instead of a newline br>   2.x:print # output New line
  3.x:print () # Output New line
  2.x:print >>sys.stderr, "Fatal error"
  3.x:print ("Fatal error", File=sys.stderr)
  2.x:print (X, y)

# Output Repr ((x, y))
3.x:print ((x, y)) # is different from print (x, y)!


7 changes the behavior of the order operator, such as X<y, when the x and Y types do not match, throw the TypeError instead of returning the bool value immediately
8 input function changed, delete raw_input, replace with input:
2.x:guess = Int (raw_input (' Enter aninteger: ') # Read the keyboard input method
3.x:guess = Int (input (' Enter aninteger: '))

9) to remove the tuple parameter solution package. Cannot def (A, (b, c)):p This defines a function
10 The new 8-character variable, the OCT () function is modified accordingly.
The 2.X approach is as follows:
>>> 0666
438
>>> Oct (438)
' 0666 '
3.X this way:
>>> 0666
Syntaxerror:invalid token (&LT;PYSHELL#63&GT;, line 1)
>>> 0o666
438
>>> Oct (438)
' 0o666 '
11 added 2 literal and bin () functions
>>> Bin (438)
' 0b110110110 '
>>> _438 = ' 0b110110110 '
>>> _438
' 0b110110110 '
12) Scalable iterative solution. In py3.x, a, b,*rest = seq and *rest, a = seq are all legitimate, requiring only two points: rest is the list
Objects and SEQ can be iterated.
13 The new super (), can no longer give super () pass parameters,
>>> class C (object):
def __init__ (Self, a):
Print (' C ', a)
>>> class D (C):
def __init (Self, a):
Super (). __init__ (a) # call super () without parameters
>>> D (8)
C 8
<__main__. D Object at 0x00d7ed90>
14 The new Metaclass syntax:
Class Foo (*bases, **kwds):
Pass
15) Support class decorator. The usage is the same as the function decorator:
>>> def foo (cls_a):
def print_func (self):
Print (' Hello, world! ')
Cls_a.print = Print_func
Return cls_a
>>> @foo
Class C (object):
Pass
>>> C (). Print ()
Hello, world!.
Class decorator can be used to play the big game of civet cats in exchange for the prince. more see pep 3129
4. Strings and byte strings
1 Now the string has only one type of STR, but it is almost the same as the 2.x version of Unicode.

2 for the byte string, see the 2nd Item of "Data type"
5. Data type
1 py3.x removes the long type and now has only one integral type--int, but behaves like 2. X version of Long
2 new bytes type, corresponding to 2. X version of the eight-bit string, which defines a bytes literal method as follows:
>>> B = B ' It '
>>> type (b)
<type ' bytes ' >
str objects and Bytes objects can be converted to each other using the. Encode () (str-> bytes) or. Decode () (bytes-> str) method.
>>> s = B.decode ()
>>> s
' I '
>>> B1 = S.encode ()
>>> B1
B ' I '
3 The Dict. Keys (),. Items, and. Values () methods return iterators, and functions such as the previous iterkeys () are discarded. And also removed from the
Dict.has_key (), replace it with in.
6. Object-oriented
1) Introduce abstract base class (Abstraact base Classes,abcs).
2 the container class and iterator class are ABCs, so the type of cellections module is much more than Py2.5.
>>> Import Collections
>>> print (' \ n '. Join (DIR (collections))
Callable
Container
Hashable
Itemsview
Iterable
Iterator
Keysview
Mapping
Mappingview
Mutablemapping
Mutablesequence
Mutableset
Namedtuple
Sequence
Set
Sized
Valuesview
__all__
__builtins__
__doc__
__file__
__name__
_abcoll
_itemgetter
_sys
Defaultdict
Deque
In addition, numeric types are ABCs. See PEP3119 and Pep 3141 for these two points.
3 The next () method of the iterator is renamed __NEXT__ () and adds the built-in function next () to invoke the __next__ () method of the iterator
4 added @abstractmethod and @abstractproperty two decorator, it is more convenient to write abstract methods (properties).
7. Abnormal
1 so the exception is inherited from Baseexception and deleted by Stardarderror
2 Removes the sequence behavior of the exception class and the. Message property
3) Replace raise Exception with raise Exception (args), args syntax
4 Capture the syntax change of the exception, introduce the AS keyword to identify the exception instance, in Py2.5:
>>> Try:
... raise Notimplementederror (' Error ')
... except Notimplementederror, error:

... print error.message
...
Error
In the Py3.0:
>>> Try:
Raise Notimplementederror (' Error ')
Except Notimplementederror as error: #注意这个 as
Print (str (error))
Error
5) exception chain, because __CONTEXT__ is not implemented in 3.0A1 version
8. Module Changes
1 Remove the Cpickle module, you can use the Pickle module instead. In the end we will have a transparent and efficient module.
2 Remove Imageop Module
3) removed Audiodev, Bastion, bsddb185, Exceptions,linuxaudiodev, MD5, Mimewriter, Mimify, Popen2,
Rexec, sets, Sha, Stringold, Strop, Sunaudiodev, timing and Xmllib modules
4 Remove the BSDDB module (published separately, can be obtained from Python "bindings" for Oracle Berkeley db)
5) Remove new module
6) Os.tmpnam () and Os.tmpfile () functions are moved to the Tmpfile module
7 Tokenize module now works with bytes. The main entry point is no longer generate_tokens, but Tokenize.tokenize ()
9. Other
1) xrange () renamed to Range (), to use range () to obtain a list, you must explicitly call:
>>> List (range (10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
2) The Bytes object cannot be hashed and does not support B.lower (), B.strip (), and B.split () methods, but for the latter two can be used B.strip (b '
\n\t\r \f ') and b.split (b ') to achieve the same purpose
3) Zip (), map (), and filter () return the iterator. The Apply (), callable (), coerce (), execfile (), reduce (), and reload
() function is removed

You can now replace callable () with Hasattr (). Hasattr () syntax such as: hasattr (String, ' __name__ ')

4) String.letters and related. Lowercase and. Uppercase are removed, please use string.ascii_letters, etc.
5 if x < y cannot be compared, throw TypeError exception. The 2.x version is a
6) that returns a pseudo random Boolean value __getslice__ series members are discarded. A[I:J] The file class is discarded based on the context conversion to a.__getitem__ (Slice (i, j)) or __setitem__ and
__delitem__ calls
7), in Py2.5:
>>> File
<type ' file ' >
in py3.x:
>>> file
Traceback (most recent call last):
File < Pyshell#120> ", line 1, in <module>
file
nameerror:name ' file ' are not defined

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.