Some of the differences between Python 2 and version 3 __python

Source: Internet
Author: User
Tags integer division

Recently in learning Python, like many beginners, the beginning of a more tangled in the end is version 2 or version 3 is the future trend. In order to avoid too many detours, special online Check the relevant information, summed up some 2 and 3 differences, a lot of content is reproduced, the great God do not despise ha ...

1. Performance

The Py3.0 runs Pystone benchmark 30% slower than Py2.5. Guido that Py3.0 has a great space for optimization, in string and plastic operations can be
To achieve good optimization results.
Py3.1 performance is 15% slower than Py2.5, and there is a lot of room for improvement.
2. Code
The py3.x source file uses Utf-8 encoding by default, which makes the following code legal:
>>> China = ' Chinese '
>>>print (China)
The
3. Grammar
1) Remove the <>, and switch to!=.
2) Remove ", all switch to REPR ()
3 keywords add as and with, and True,false,none
4) Integer division returns the floating-point number, to get the integer result, use//
5) Add the nonlocal statement. External (Non-global) variables can be assigned directly using noclocal x


4, Print function

Although the print syntax is a small change in Python 3 and should already be well known, it is worth mentioning that the print statement in Python 2 is replaced by the print () function in Python 3, which means that the Python You must enclose the object you want to output in parentheses in 3.

It is also possible to use extra parentheses in Python 2. But conversely, when you want to call the print function without parentheses in the form of Python2 in Python 3, the syntaxerror is triggered.

Python 2

print ' Python ', python_version ()

print ' Hello, world! '

Print (' Hello, world! ')

Print "text",; print ' Print more Texton 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 line ')

Python 3.4.1

Hello, world!.

Some text, print more text on the same line

print ' Hello, world! '

File "<ipython-input-3-139a7c5835bd>", line 1

print ' Hello, world! '

^

Syntaxerror:invalid syntax

Note:

In Python, it is normal to output "Hello world" with no parentheses. But if you output multiple objects in parentheses at the same time, a tuple is created, because in Python 2, print is a statement, not a function call.

print ' Python ', python_version ()

Print (' A ', ' B ')

print ' A ', ' B '

Python 2.7.7

(' A ', ' B ')

A b

5. Integer division

Since it is often overlooked that Python 3 changes in integer division (which does not trigger syntax error), you need to pay special attention to this change when porting code or executing Python 3 code in Python 2.

So I'm going to try using float (3)/2 or 3/2.0 instead of 3/2 in the Python 3 script to avoid the error that the code might cause in the Python 2 environment (or, conversely, in Python 2 script, use the From __future__import Division to use the division of Python 3.

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

6, Xrange

In Python 2.x, a xrange () is often used to create an iterative object, usually appearing in a for loop or list/set/dictionary derivation.

This behavior is very similar to the generator (such as "lazy evaluation"), but the xrange-iterable here is endless, meaning that it is possible to iterate infinitely on this xrange.

Because of Xrange's "lazy knowledge" feature, range () is usually faster than xrange () if you only need to iterate once (for example, in a For loop). It is not recommended to use range () in multiple iterations, however, because range () will regenerate a list in memory each time.

In Python 3, range () is implemented in the same way as the xrange () function, so there is no dedicated xrange () (using xrange () in Python 3 triggers nameerror).

Import Timeit

n = 10000

def test_range (n):

Return to 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_xrange (N)

Python 2.7.6

Timing Range ()

1000 loops, best 3:433µs per loop

Timing Xrange ()

1000 loops, best 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 3:520µs per loop

Print (Xrange (10))

---------------------------------------------------------------------------

Nameerror Traceback (most recent call last)

In ()

----> 1 Print (xrange (10))

Nameerror:name ' xrange ' is not defined


A reply from the great God

Author: Wang Cat
Link: http://www.zhihu.com/question/19698598/answer/12704353
Source: Know

> 1. Print is no longer a statement, but a function, such as print ' ABC ' and now print (' abc ')
However, python2.6+ can use the from __future__ import print_function to achieve the same functionality
> 2. In Python 3, there are no legacy classes, only new classes, that is, no more class Foobar (object) Like this: pass explicitly subclass object
But it's best to add. The main difference is that Old-style is ClassType type and New-style is type
> 3. The original 1/2 (two integer division) result is 0, now is 0.5
Python 2.2+ can use the From __FUTURE__ Import Division to implement the change feature, and note//replace the previous/operation
> 4. New string formatting method format replaces%
Error, starting with python2.6+ already has this method in Str and Unicode, while Python3 still supports% operator
> 6. Xrange Rename to Range
Also, there are a series of built-in functions and methods that return the iterator object instead of the list or tuple, such as filter, map, Dict.items, etc.
> 7. != Replacement < >
Python2 very few people use < > so it's not a change.
> 8. Long Rename to int
Not exactly, Python3 completely abandoned the method of Long+int double integer implementation, unified as int, support high-precision integer operation.
> 9. Except Exception, E becomes except (Exception) as E
Only python2.5 and the following version do not support this syntax. The python2.6 is supported. It's not new.
> 10. exec becomes a function
A change similar to print () preceded by a statement.

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.