The main differences between "go" python 2.7.x and Python 3.x

Source: Internet
Author: User
Tags integer division



Original link: http://www.kuqin.com/shuoit/20140728/341451.html



Many Python beginners want to know which version of Python they should start learning from. My answer to this question is "you learn the version of the tutorial you like and then check the differences between them." "



But what if you start a new project and have a choice? I would like to say that there is no right or wrong, as long as you plan to use the library Python 2.7.x and Python 3.x both sides support words. Nonetheless, when writing any of these code, or when you plan to transplant your project, it is worth looking at the differences between these two major popular Python versions in order to avoid common pitfalls

Chapter
    • Using__future__modules
    • printFunction
    • Integer Division
    • Unicode
    • Xrange
    • Raising exceptions
    • Handling Exceptions
    • next()Functions and.next()methods
    • For loop variables and global namespace leaks
    • Compare non-sortable types
    • Byinput()parsing the user's input
    • Returns an iterative object instead of a list
    • More articles on Python 2 and Python 3
FutureModule


Some Python 2 incompatible keywords and features introduced in Python 3.x can be imported through the built-in modules in Python 2__future__. If you plan to have your code support Python 3.x, it is recommended that you use__future__module import. For example, if I want to represent the integer division in Python 3.x in Python 2, we can import it by following


From __future__ Import Division


More__future__modules that can be imported are listed in the following table:


inin
feature Optional Mandatory effect
Nested_scopes 2.1.0b1 2.2 PEP 227:statically Nested Scopes
Generators 2.2.0a1 2.3 PEP 255:simple Generators
Division 2.2.0a2 3.0 PEP 238:changing the Division Operator
Absolute_import 2.5.0a1 3.0 PEP 328:imports:multi-line and Absolute/relative
With_statement 2.5.0a1 2.6 PEP 343:the "with" Statement
Print_function 2.6.0a2 3.0 PEP 3105:make Print a function
Unicode_literals 2.6.0a2 3.0 PEP 3112:bytes literals in Python 3000


(source:https://docs.python.org/2/library/future.html)


From platform import python_version
PrintFunction


[Skip to Chapter preview]



Trivial, andprintgrammatical changes are probably the most well-known, but it's worth mentioning that the Python 2printdeclaration has beenprint()replaced by a function, which means we have to wrap the object we want to print in parentheses.
Python 2 does not have an extra parenthesis problem. In contrast,printpython 3 throws a syntax exception () If we do not use parentheses to invoke the function in the way Python 2 doesSyntaxError.



Python 2


print ' Python ', python_version () print ' Hello, world! ' print (' Hello, world! ') print "text",; print ' Print more text in the same line '

Python 2.7.6 Hello, world! Hello, world!. Text print more text on the same line


Python 3


Print (' Python ', Python_version ()) print (' Hello, world! ') print ("Some text,", end= "") print (' Print more ' text on the same l Ine ')

Python 3.4.1 Hello, world! Some text, print more text in the same line

print ' Hello, world! '

File "", Line 1 print ' Hello, world! ' ^ syntaxerror:invalid syntax


 


Attention



The above using Python 2Printing "Hello, World"is very normal, though, if you have multiple objects in parentheses, we will create a tuple becauseprintin Python 2 is a declaration, not a function call.


print ' Python ', Python_version () print (' A ', ' B ') print ' A ', ' B '

Python 2.7.7 (' A ', ' B ') a B


 
divisible 


[Skip to Chapter preview]



If you are porting code, this change is particularly risky. Or you execute the Python 3 code on Python 2. Because the change in this division is reflected in the fact that it is ignored (that is, it does not throw a syntax exception).



So I'm still inclined to use one or the other infloat(3)/23/2.0my Python 3 script to save some of the trouble in Python 23/2(and instead come over as well, I recommend it in your Python 2 scriptfrom __future__ import division)



Python 2


print ' Python ', python_version () print ' 3/2 = ', 3/2 print ' 3//2 = ', 3//2 print ' 3/2.0 = ', 3/2.0 print ' 3//2. 0 = ', 3//2.0

Python 2.7.6 3/2 = 1 3//2 = 1 3/2.0 = 1.5 3//2.0 = 1.0



Python 3


Print (' Python ', Python_version ()) print (' 3/2 = ', 3/2) print (' 3//2 = ', 3//2) print (' 3/2.0 = ', 3/2.0) print (' 3/ /2.0 = ', 3//2.0)

Python 3.4.1 3/2 = 1.5 3//2 = 1 3/2.0 = 1.5 3//2.0 = 1.0


Unicode


[Skip to Chapter preview]



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



Now, in Python 3, we end up with aUnicode (utf-8)string, and a byte class:byteandbytearrays.



Python 2


print ' Python ', python_version ()

Python 2.7.6


Print type (Unicode (' This was like a python3 str type '))

Print type (b ' byte type does not exist ')

print ' They is really ' + B ' the same ' they is really the same

Print type (ByteArray (b ' ByteArray oddly does exist though '))


Python 3


Print (' Python ', Python_version ()) print (' Strings is now utf-8 u03bcnicou0394é! ') Python 3.4.1 Strings is now utf-8μnicoδé!

Print (' Python ', python_version (), end= "") print (' Have ', type (b ' bytes for storing data ')) Python 3.4.1 have

Print (' and Python ', python_version (), end= "") print (' also has ', type (ByteArray (b ' bytearrays '))) and Python 3.4.1 also have

' Note that we cannot add a string ' + B ' bytes for data '------------------------------------------------------------------ ---------TypeError Traceback (most recent call last) in ()----> 1 ' Note so we cannot add a string ' + B ' bytes for DA Ta ' typeerror:can ' t convert ' bytes ' object to str implicitly


Xrange


[Skip to Chapter preview]



Thexrange()use of creating iterative objects in Python 2 is very popular. For example, a for loop or a list/set/dictionary derivation.



This behaves much like a generator (e.g.. "Lazy evaluation"). But thisxrange-iterableis infinite, which means you can traverse infinitely.



Because of its lazy evaluation, if you must not simply not traverse it once, thexrange()function isrange()faster (such as for Loop). However, it is not recommended that you repeat iterations more than once, because the generator starts from scratch each time.



In Python 3,range()it is implemented like that so thatxrange()a specializedxrange()function no longer exists (a named exception is thrown in Python 3xrange()).


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 ' nntiming xrange () '%timeit Test_xran  GE (n) Python 2.7.6 Timing range () loops, Best of 3:433µs per loop timing xrange () + 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 () loops, b EST of 3:520µs per loop

Print (xrange)---------------------------------------------------------------------------nameerror Traceback (most recent call last) in ()----> 1 print (xrange) nameerror:name ' xrange ' are not defined


rangemethods for objects in Python 3__contains__



Another thing worth mentioning is thatrangethere is a new method in Python 3__contains__(thanks to Yuchen Ying for pointing this out), the__contains__method accelerates the"查找"significant integers and Boolean types in Python 3.x.


x = 10000000 def val_in_range (X, Val): Return Val in range (x) def val_in_xrange (X, Val): Return Val in xrange (x) print (' Py Thon ', python_version ()) Assert (Val_in_range (x, X/2) = = True) assert (Val_in_range (x, X//2) = = True)%timeit Val_in_range ( X, X/2)%timeit val_in_range (x, X//2) Python 3.4.1 1 loops, Best of 3:742 ms Per loop 1000000 loops, Best of 3:1.19µs P ER Loop


Based on thetimeitresults above, when it makes an integer type, instead of a floating-point type, you can see that the speed of performing the lookup is 60,000 times times faster. However, because Python 2.xrangeorxrangenot a__contains__method, this integer type or floating-point type of query speed will not be too large.


print ' Python ', Python_version () assert (Val_in_xrange (x, x/2.0) = = True) assert (Val_in_xrange (x, X/2) = = True) assert (Val _in_range (x, X/2) = = True) assert (Val_in_range (x, X//2) = = True)%timeit val_in_xrange (x, x/2.0)%timeit val_in_xrange (x,  X/2)%timeit val_in_range (x, x/2.0)%timeit val_in_range (x, X/2) Python 2.7.7 1 loops, Best of 3:285 ms per loop 1 loops, Best of 3:179 ms per loop 1 loops, Best of 3:658 ms per loop 1 loops, Best of 3:556 ms Per loop


The following__contain__method does not add to the evidence in Python 2.x:


Print (' Python ', Python_version ()) range.__contains__ Python 3.4.1

print ' Python ', python_version () range.__contains__ python 2.7.7--------------------------------------------------- ------------------------Attributeerror Traceback (most recent call last) in () 1 print ' Python ', python_version ()---- ; 2 range.__contains__ attributeerror: ' Builtin_function_or_method ' object has no attribute ' __contains__ '

print ' Python ', python_version () xrange.__contains__ python 2.7.7-------------------------------------------------- -------------------------Attributeerror Traceback (most recent call last in () 1 print ' Python ', python_version ()---- ; 2 xrange.__contains__ Attributeerror:type object ' xrange ' has no attribute ' __contains__ '


* * Note the different speeds in Python 2 and python 3 * * *



Some apes point to arange()different speed between Python 3 and Python 2xrange(). Because they are implemented in the same way, they expect the same speed. Nonetheless, the fact is that Python 3 tends to run slower than Python 2.


Def test_while (): i = 0 while I < 20000:i + = 1 return

Print (' Python ', Python_version ())%timeit test_while () python 3.4.1 loops, best of 3:2.68 ms Per loop

print ' Python ', python_version ()%timeit test_while () python 2.7.6 loops, best of 3:1.72 ms Per loop

 Raising exceptions 


[Skip to Chapter preview]



Python 2 accepts both old and new syntax tags, and in Python 3 it blocks (and in turn throws a syntax exception) if I use parentheses to enclose exception parameters.



Python 2


print ' Python ', python_version () Python 2.7.6

Raise IOError, "File Error"---------------------------------------------------------------------------IOError Traceback (recent call last) in ()----> 1 raise IOError, "File Error" Ioerror:file error

Raise IOError ("File Error")---------------------------------------------------------------------------IOError Traceback (recent call last) in ()----> 1 Raise IOError ("File error") Ioerror:file error


Python 3


print (' Python ', Python_version ()) Python 3.4.1

Raise IOError, "File Error"

File "", line 1 raise IOError, "file error" ^ Syntaxerror:invalid syntax the proper-to raise a exception in Python 3 :

Print (' Python ', Python_version ()) Raise IOError ("File Error") Python 3.4.1------------------------------------------ ---------------------------------OSError Traceback (most recent call last) in () 1 print (' Python ', python_version ())---- > 2 Raise IOError ("File error") Oserror:file error


Handling Exceptions


Handling Exceptions in Python 3 has also changed slightly, and in Python 3 we now use themasas keywords.



Python 2


print ' Python ', python_version () Try:let_us_cause_a_nameerror except Nameerror, Err:print err, '--Our error message ' Python 2.7.6 name ' Let_us_cause_a_nameerror ' is not defined--our error message


Python 3


Print (' Python ', Python_version ()) Try:let_us_cause_a_nameerror except Nameerror as Err:print (err, '--Our error mess Age ') Python 3.4.1 name ' Let_us_cause_a_nameerror ' was not defined--our error message
Next () function and. Next () method


Becausenext() (.next())it is such a normal use of the function (method), there is another syntax change (or the implementation has changed), it is worth mentioning: in Python 2.7.5 functions and methods you can use, thenext()function in Python 3 has been preserved (call.next()Throws a property exception).



Python 2


print ' Python ', python_version () My_generator = (letter to letter in ' ABCDEFG ') Next (My_generator) My_generator.next ()

Python 2.7.6 ' B '


Python 3


Print (' Python ', Python_version ()) My_generator = (letter to letter in ' ABCDEFG ') Next (My_generator)

Python 3.4.1 ' a '

My_generator.next ()

---------------------------------------------------------------------------Attributeerror Traceback (most recent Call last) in ()----> 1 my_generator.next () Attributeerror: ' Generator ' object have no attribute ' next '

For loop variables and global namespace leaks


Good news: The For loop variable in Python 3.x no longer causes namespace leaks.



A change has been made in Python 3.x, as described in the What's New in Python 3.0:


"List deduction no longer supports [... for var in item1, Item2, ...] Such a syntax. Replace with [... for Var in (item1, item2, ...)]. It is also important to note that list derivation has different semantics: they shut down the syntax sugar of the generator expression in the ' list () ' constructor, and in particular the loop control variable no longer leaks into the surrounding scope. "


Python 2


print ' Python ', python_version () i = 1 print ' before:i = ', I print ' comprehension: ', [I for I in range (5)] print ' After: i = ', I Python 2.7.6 before:i = 1 Comprehension: [0, 1, 2, 3, 4] after:i = 4


Python 3


Print (' Python ', python_version ()) i = 1 print (' before:i = ', i) print (' Comprehension: ', [I for I in range (5)]) print (' Afte R:i = ', i) Python 3.4.1 before:i = 1 Comprehension: [0, 1, 2, 3, 4] after:i = 1
Compare non-sortable types


Another change in Python 3 is that when you compare a non-sorted type, a type error is thrown.



Python 2


print ' Python ', python_version () print "[1, 2] > ' foo ' =", [1, 2] > ' foo ' Print "(1, 2) > ' foo ' =", (1, 2) >  ' foo ' print "[1, 2] > (1, 2) =", [1, 2] > (1, 2) Python 2.7.6 [1, 2] > ' foo ' False (1, 2) > ' foo ' = True [1, 2] > (1, 2) = False


Python 3


Print (' Python ', Python_version ()) Print ("[1, 2] > ' foo ' =", [1, 2] > ' foo ') print ("(1, 2) > ' foo ' =", (1, 2) &G T ' foo ') print ("[1, 2] > (1, 2) =", [1, 2] > (1, 2)) Python 3.4.1--------------------------------------------------- ------------------------TypeError Traceback (most recent call last) in () 1 print (' Python ', python_version ())----> 2 Print ("[1, 2] > ' foo ' =", [1, 2] > ' foo ') 3 print ("(1, 2) > ' foo ' =", (1, 2) > ' foo ') 4 print ("[1, 2] > ( 1, 2) = ", [1, 2] > (1, 2)) typeerror:unorderable types:list () > str ()
Passinput()Parsing the user's input


Fortunately, the problem of storing user input as an object has been resolved in Python 3str. In order to avoid the dangerous behavior of reading non-string types in Python 2, we have to useraw_input()instead.



Python 2


Python 2.7.6 [GCC 4.0.1 (Apple Inc. build 5493)] on Darwin Type ' help ', ' copyright ', ' credits ' or ' license ' for more infor Mation. >>> my_input = input (' Enter a number: ') Enter a number:12 >>> type (my_input) >>> my_input = R Aw_input (' Enter a number: ') Enter a number:123 >>> type (my_input)


Python 3


Python 3.4.1 [GCC 4.2.1 (Apple Inc. build 5577)] on Darwin Type ' help ', ' copyright ', ' credits ' or ' license ' for more infor Mation. >>> my_input = input (' Enter a number: ') Enter a number:12 >>> type (my_input)
Returns an iterative object instead of a list


If you see in the Xrange section, now some methods and functions in Python 3 return the Iteration object--instead of the list in Python 2



Because we usually have those traversal only once, I think this change is very meaningful for saving memory. However, it is also possible, relative to the generator---to traverse multiple times as needed. It is not so efficient.



And for those cases, what we really need is a list object, and we canlist()simply convert the iterative object to a list by using the function.



Python 2


print ' Python ', python_version () print range (3) Print type (range (3)) Python 2.7.6 [0, 1, 2]


Python 3


Print (' Python ', Python_version ()) Print (range (3)) print (Type (range (3))) Print (List (range (3)) Python 3.4.1 Range (0, 3) [0, 1, 2]


in Python 3, some frequently used functions and methods that do not return a list are :


    • Zip ()

    • Map ()

    • Filter ()

    • Dictionary ' s. Keys () method

    • Dictionary ' s. Values () method

    • Dictionary ' s. Items () method

More articles on Python 2 and Python 3


Here are some good articles that I recommend following for Python 2 and Python 3.



Porting to Python 3


    • Should I use Python 2 or Python 3 for my development activity?

    • What ' s New in Python 3.0

    • Porting to Python 3

    • Porting python 2 Code to Python 3

    • How keep Python 3 moving forward


Supporters and opponents of Python 3


    • Awesome features of Python you can ' t use because you refuse to upgrade to Python 3

    • Everything you didn't want to know about Unicode in Python 3

    • Python 3 is killing Python

    • Python 3 can revive Python

    • Python 3 is fine


The main differences between "go" python 2.7.x and Python 3.x


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.