In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article is to share with you about the difference between Python2.x and 3.x. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
Version 3.0 of Python is often referred to as Python 3000, or Py3k for short. This is a big upgrade compared to earlier versions of Python.
In order not to bring too much burden, Python 3.0 was not designed with downward compatibility in mind.
Many programs designed for earlier versions of Python do not work properly on Python 3.0.
To take care of existing programs, Python 2.6, as a transitional version, basically uses the syntax and libraries of Python 2.x, while taking into account the migration to Python 3.0, allowing for the use of some Python 3.0syntax and functions.
The new Python program recommends using Python version 3. 0 syntax.
Unless the running environment cannot install Python 3.0 or the program itself uses a third-party library that does not support Python 3.0. Currently, third-party libraries that do not support Python 3.0are Twisted, py2exe, PIL, etc.
Most third-party libraries are working hard to be compatible with Python 3.0. Even if you cannot use Python 3.0 immediately, it is recommended that you write a program that is compatible with Python 3.0, and then use Python 2.6and Python 2.7to run it.
The changes in Python 3.0 are mainly in the following aspects:
Print function
The print statement is gone and replaced by the print () function. Python 2.6and Python 2.7partially 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 there is a space after print print ("fish") # print () cannot take any other parameters
However, Python 2.6 actually supports the new print () syntax:
From _ _ future__ import print_functionprint ("fish", "panda", sep=',') Unicode
Python 2 has an ASCII str () type, and unicode () is a separate type, not a byte type.
Now, in Python 3, we finally have the Unicode (utf-8) string and a byte class: byte and bytearrays.
Because 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 Beijing Tiananmen" > str'\ xe6\ x88\ X91\ xe7\ X88\ xb1\ xe5\ X8c\ X97\ xe4\ xac\ xe5\ xa4\ xa9\ xe5\ xae\ x89\ xe9\ x97\ xa8' > str = u "I love Beijing Tiananmen" > > stru'\ u6211\ u7231\ u5317\ u4eac\ u5929\ u5b89\ u95e8'
Python 3.x
Str = "I love Beijing Tiananmen" > str' I love Beijing Tiananmen division operation
Division in Python is more high-end than other languages, with a complex set of rules. Division in Python has two operators, / and / /
First of all, let's say / divide:
In python 2.x / division is similar to most languages we are familiar with, such as Java and C, the result of integer division is an integer, the decimal part is completely ignored, and floating point division retains the decimal point to get a floating point result.
In python 3.x / division no longer does this, and for division between integers, the result will also be a floating point number.
Python 2.x:
> > 1 / 20 > > 1.0 / 2.00.5
Python 3.x:
> 1Universe 20.5
For / / division, this division is called floor division and automatically performs a floor operation on the result of the 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 instead of discarding the decimal part, the floor operation is performed. If you want to intercept the integer part, you need to use the trunc function of the math module
Python 3.x:
> import math > math.trunc (1 / 2) 0 > math.trunc (- 1 / 2) 0 exception
Handling exceptions has also changed slightly in Python 3, where we now use as as the keyword in Python 3.
The syntax for catching exceptions has been changed from except exc and var 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 both grammars.
1. In the 2.x era, all types of objects can be thrown directly, and in the 3.x era, only objects inherited from BaseException can be thrown.
2.x raise statement uses commas to separate thrown object types from parameters. 3.x cancels this weird way of writing and simply calls the constructor to throw the object.
In the 2.x era, exceptions in the code not only represent program errors, but also often do what ordinary control structures should do. in 3.x, it can be seen that designers make exceptions more specialized. only when an error occurs can it be handled with an exception catch statement.
Xrange
The use of xrange () to create iterative objects is very popular in Python 2. For example: for loop or list / collection / dictionary derivation.
This behaves very much like a generator (for example. "lazy evaluation"). But the xrange-iterable is infinite, which means you can traverse infinitely.
Because of its lazy evaluation, the xrange () function is faster than range () if you have to traverse it more than once (such as the for loop). However, compared to one iteration, it is not recommended that you repeat the iteration many times, because the generator starts from scratch each time.
In Python 3, range () is implemented like xrange () so that a special xrange () function no longer exists (in Python 3, xrange () throws a named exception).
Import timeitn = 10000def test_range (n): return for i in range (n): passdef 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.6timing range () 1000 loops, best of 3: 433 μ s per looptiming 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.1timing range () 1000 loops Best of 3: 520 μ s per loopprint (xrange (10))-NameError Traceback (most recent call last) in () > 1 print (xrange (10)) NameError: name 'xrange' is not defined octal literal representation
The octal number must be written as 0o777, the original form 0777 cannot be used, and the binary must be written as 0b111.
A new bin () function is added to convert an integer to a binary string. Python 2.6 already supports both grammars.
In Python 3.x, there is only one way to represent octal literals, and that is 0o1000.
Python 2.x
> 0o1000512 > 01000512
Python 3.x
> 01000 File "", line 1 01000 ^ SyntaxError: invalid token > 0o1000512 unequal operator
Python 2.x does not mean that there are two ways to write it! = and
Python 3.x has been removed, and there is only one way to write it. Fortunately, I have never used it.
Removed repr expression ``
The reverse quotation mark ``in Python 2.x is equivalent to the function of repr function.
Python 3.x removes ``and only allows the use of the repr function. Is this in order to make the code look clearer? However, I feel that there are few opportunities to use repr, usually only when using debug, and most of the time I still use the str function to describe objects in terms of strings.
Def sendMail (from_: str, to: str, title: str, body: str)-> bool: pass multiple modules have been renamed (according to PEP8) the old name, the new name _ winregwinregConfigParserconfigparsercopy_regcopyregQueuequeueSocketServersocketserverreprreprlib
The StringIO module is now merged into the new io module. New, md5, gopherlib and other modules have been deleted. Python 2.6 already supports the new io module.
Httplib, BaseHTTPServer, CGIHTTPServer, SimpleHTTPServer, Cookie, cookielib are merged into the http package.
The exec statement is canceled, leaving only the exec () function. The exec () function is already supported in Python 2.6.
5. Data type
1) Py3.X removes the long type, and now there is only one integer-- int, but it behaves like the 2.x version of long
2) A new bytes type has been added, corresponding to the octet string in version 2.x. The method to define a literal quantity of bytes is as follows:
> type (b)
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' china' > b1 = s.encode () > b1 b1bcm
3) the .keys (), .items, and .values () methods of dict return iterators, while previous functions such as iterkeys () are discarded. Also removed is dict.has_key (). Replace it with in.
[supplement]-
Original:
File (. ) or open (.)
Change to use only
Open (.)
Enter a string from the keyboard
Original:
Raw_input ("prompt message")
Change to:
Input ("prompt message")
In python2.x, both raw_input () and input () functions exist, where the difference is:
Raw_input ()-treats all inputs as strings and returns the string type
Input ()-can only receive "numeric" input, and has its own characteristics when dealing with pure digital input. It returns the type of the entered number (int, float).
Raw_input () and input () are integrated in python3.x, removing raw_input (), leaving only the input () function, which accepts arbitrary input, defaults all inputs to string processing, and returns a string type.
Map, filter and reduce
These three functions are claimed to be representatives of functional programming. There is also a big difference between Python3.x and Python2.x.
First of all, let's simply type map and filter under the interaction of Python2.x, and see that the type of both is built-in function (built-in function):
> > map > filter >
The type of result they output is a list:
> map (lambda XRV x * 2, [1Mei 2jue 3]) [2,4,6] > filter (lambda XRX% 2 = = 0penny range (10)) [0,2,4,6,8] > >
But in Python 3.x, they don't look like this:
> map > map (print, [1Jing 2jue 3]) > filter > filter (lambda x filter% 2 = = 0, range (10)) >
First, they have changed from a function to a class, and second, their return result has changed from the original list to an iterable object, so we try to iterate manually with the next function:
> f = filter (lambda x range% 2 = = 0, range (10)) > next (f) 0 > next (f) 2 > next (f) 4 > next (f) 6 > Thank you for reading! This is the end of the article on "what is the difference between Python2.x and 3.x version". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.