Learn Python 2 or Python 3?

I really feel sorry to see many new students hesitate to learn Python 2 or Python 3, wasting a lot of time and missing the opportunity of promotion and salary increase. So, I can’t resist the temptation to be rude and give you a rude and correct answer:

Should YOU learn Python 2 or Python 3?

To learn!

This answer may be unexpected and easy to refute, for example:

  • Python 3 is the future of Python
  • The official Python recommendation refers to learning Python 3 directly
  • Python 2 is only maintained until 2020

Is it really so? As an engineer working for a front-line Internet company and a Python veteran, here’s why.

Interested persons can add QQ to communicate: 3271330538 white piao information please click 666

Why learn Python 2

Python 2 only maintained until 2020 should not be a reason to reject Python 2

Anyone struggling to learn Python 2 or Python 3 knows that Python 2 is only available until 2020, according to Python’s official plan. Python 2 will only be available until 2015 (github.com/python/peps…) . So, as you can see, skipping tickets is not the prerogative of The Chinese, and Python officials will skip tickets as well.

If you follow the tech news, you will notice that just a few days ago, Microsoft announced that they will stop all support for Windows 7 in 2020. After that, they will not fix any bugs and security issues, just like XP does now. However, if you look at the colleagues, friends and relatives around us, are they more likely to use Windows 7 or Windows 10? Are any of these Windows 7 people screaming that I need to upgrade Windows? Are Windows 10 users screaming for Windows 7 users to upgrade?

However, in the Python world, there are just too many people clamoring for others to upgrade Python 3. Most of the time users don’t care if they use Python 2 or Python 3, as long as it works. So, people who use Python 2 have little incentive to upgrade to Python 3.

If you think Python 3 is the future of Python, you don’t want to touch Python 2 projects. So, here’s the question, goddess tells you, come to my house tonight and fix my computer, but my computer is Windows XP, do you want to go or not?

Python’s official recommendation to learn Python 3 is wishful thinking

Download statistics of Python 2 and Python 3 (Python 2.7 still Reigns supreme in PIP Mouse) :

Python 2 is far more used than Python 3. And notice that the units of the vertical axis are exponents! A simple translation shows that Python 2.7 was 90% of the total downloads in terms of downloads alone! So, learning Python, it’s almost impossible to get rid of Python 2 and learn Python 3.

The data above are global statistics, let’s take a look at the Situation of the Internet in China. In order to write this article, I sent a red envelope to my classmates and invited front-line technical experts from Baidu, Alibaba, Tencent, netease, Meituan, Huawei, China Merchants Bank, CCB, eBay, Meitu, Oracle and other companies to make statistics on the use of Python by major companies.

The statistics are as follows:

  • 10% use Python 3
  • 20% use both Python 2 and Python 3, and more Python 2
  • 70% use Python 2

The statistics are consistent with pYPI’s global statistics. So, if you say, I started with Python 3, Python 3 is the future of Python, and I don’t want to learn about Python 2. Well, you might miss half of China’s Internet. Maybe you don’t care, but what if someone pays you to maintain Python 2 code?

Python 2 will be around for a long time

Have you ever wondered why Python officials are pushing people to use Python 3 when Python 2 is still dominant?

The answer is simple and brutal: most people will take what you give them. As FAR as I know, Although Python 3 was released in December 2008, Python 3 is still not the default Python interpreter for any operating system, which is the main reason why Python 3 is not widely used.

We all know that in any company, upgrading the operating system version of a server is a very serious matter. So it’s reasonable to believe that Python 2 will be around for a long time. How long is very long? At least longer than 2020.

The world is not black and white, and neither is Python

Given the previous data, shouldn’t we be learning Python 2? Why both Python 2 and Python 3?

First, the world is not black and white, and neither is Python. There is a fine balance between learning Python 2 and learning Python 3, which is compatibility with both Python 2 and Python 3. To be compatible with both Python 2 and Python 3, you need to make deep use of Python’s Future library. The Future library contains a number of features from Python 3 backport to Python 2. Fully utilizing the Future library, it is compatible with Python 2 and Python 3.

Second, there are some differences between Python 2 and Python 3, but not as much as you might think. The difference between Python 2 and Python 3 is less than 10% of Python syntax. We can quickly see which Python 2 syntax has been deprecated in Python 3. As we write code, we can avoid this part of the syntax. As a Python best practice, Python syntax deprecated in Python 3 is not recommended in Python 2, or it would not be deprecated. If you know and adhere to Python best practices, then the difference between Python 2 and Python 3 is even smaller for you.

Finally, we can refer to good open source software practices, such as OpenStack, and strive to make the code compatible with Python 2 and Python3 (Python3-openstack), or some open software libraries (such as SIX). If we can be compatible with both Python 2 and Python 3, we will have a wider audience and our code will be more valuable.

Take Windows. When Windows 7 was released (and I’m not going to mention Vista), many people still clung to XP. When you asked them why, they would say in a straight voice, “It sucks,” or “A lot of software isn’t compatible,” or “It’s a big change. Or even, “XP is already a good system, Microsoft just came out with a new one to make money.”

As a result, spring came and spring came again. After Losing Win 7, we came back to Win 8, but these people still have the same ideas (I believe this is more the case among Chinese people). If there are a lot of these people and this continues, the end result is that Microsoft is going to get worse and worse, and people are going to have no choice but to surrender to Linux. How do you have a feeling of elation.

When I mentally switched from Windows XP to Python 2, Windows 7 to Python 3, or even Python 4, I felt a panic that I had almost conspired with others to kill Python! Just imagine, after many years, Ruby, Go and other languages have many new features. Although the latest Python is very good, it will fall out of use because some people refuse to change, stick to the old version and throw out some ridiculous excuses. The efforts of Guido and the Python community as a whole have been ignored by these people’s habits.

Let’s take a look at these ridiculous reasons (for a detailed explanation, please refer to xu Fengquan’s answer on Zhihu, which I’ll briefly summarize here) : What? Too few libraries to support Python 3? Wake up, it’s been 6 years, last 3.4.1, and libraries that don’t support Python 3 are mostly unmaintained for years. What? Poor compatibility between the new version and the old version? Rest assured, future versions will be less and less compatible, unless you plan to stick with Python 2 forever. Besides, is it so hard to change for the sake of new features? Finally, for those of you who are stuck with the old version, aren’t you really justifying your problems with a bunch of excuses and criticisms?

stop talking, just do it

Here are some of my thoughts on learning Python 2 vs. Python 3:

  • Before learning Python, take a look at the Python 2 syntax deprecated in Python 3. Don’t spend too much time walking through these parts
  • Use Python 2, not Python versions prior to 2.7
  • Use Python 3, not Python prior to 3.4
  • Learn more about Python 2’s Future library
  • Instead of maintaining separate branches for Python 2 and Python 3 for the same piece of code, try to make Python 2 and Python 3 compatible in one set of code

This article explains in detail why you should learn Python 2 and Python 3 together, and how to find a balance between Python 2 and Python 3. However, the important thing is not to struggle with learning Python 3 or Python 2, but to “stop talking, just do it!” .

Specific differences between Python2 and Python3

In addition to introducing import from Future, it is important to understand the difference between the two

Print function :(in Python3 print is a function and must be enclosed in parentheses; Python2: print to class

Python 2’s print declaration has been replaced by the print() function, which means we have to wrap the object we want to print inside the parentheses.

Python 2

1 print ‘Python’, python_version()

2 print ‘Hello, World! ‘

3 print(‘Hello, World! ‘)

4 print “text”, ; print ‘print more text on the same line’

Run result: Python 2.7.6 Hello, World! Hello, World! text print more text on the same line

Python 3

1 print(‘Python’, python_version())

2 print(‘Hello, World! ‘)

3 print(“some text,”, end=””)

4 print(‘ print more text on the same line’)

Run result: Python 3.4.1 Hello, World! some text, print more text on the same line

Parsing user input through input() :(in Python3 input is STR; Python2 input is an int, Python2 raw_INPUT is a STR. Python3 uses input and Python2 uses row_input

Fortunately, the problem of storing user input as a STR object has been solved in Python 3. To avoid the dangerous behavior of reading non-string types in Python 2, we had to use raw_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 information.

>>> my_input = input('enter a number: ') enter a number: 123 >>> type(my_input)<type 'int'> >>> my_input = raw_input('enter a number: ') enter a number: 123 >>> type(my_input)<type 'str'>
Copy the code

Python 3 Python 3.4.1 [GCC 4.2.1 (Apple Inc. Build 5577)] on Darwin Type “help”, “copyright”, Credits or License for more information.

>>> my_input = input('enter a number: ') enter a number: 123 >>> type(my_input)<class 'str'>
Copy the code

Full division :(not much effect) (Python3 / for true division, % for mod, // for floor division (result rounded); In Python3, // is true division, % is mod, and // is rounded; Python2 uses the decimal point/to indicate true division, % to indicate mod, and // to round the result

Python 2

1 print ‘Python’, python_version()

2 print ‘3 / 2 =’, 3 / 2

3 print ‘3 // 2 =’, 3 // 2

4 Print ‘3/2.0′ =’, 3/2.0

5 print ‘3 // 2.0 =’, 3 // 2.0

Run result: Python 2.7.6 3/2 = 1 3 // 2 = 1 3/2.0 = 1.5 3 // 2.0 = 1.0

Python 3

1 print(‘Python’, python_version())

2 print(‘3 / 2 =’, 3 / 2)

3 print(‘3 // 2 =’, 3 // 2)

4 Print (‘ 3/2.0 =’, 3/2.0)

Print (‘3 // 2.0 =’, 3 // 2.0) k run result: Python 3.4.1 3/2 = 1.5 3 // 2 = 1 3/2.0 = 1.5 3 // 2.0 = 1.0

Xrange module:

In Python 3, range() is implemented like xrange() so that a dedicated Xrange () function no longer exists (xrange() throws named exceptions in Python 3).

The use of xrange() to create iterators is very popular in Python 2. For example, a for loop or a list/set/dictionary derivation. This behavior is very generator like (e.g. “Lazy evaluation”). But this xrange-iterable is infinite, which means you can iterate over it indefinitely. Because of its lazy evaluation, the xrange() function is faster than range() if you have to go through it only once (for example). However, it is not recommended that you iterate more than once, since the generator starts from scratch each time.

|

Python 2.4 compared to Python 3.0

Print changes from statement to function

Print 1, 2+3

Print (1, 2+3)

Range and xrange

Range (0, 4) results in a list [0,1,2,3]

List (range(0,4))

Xrange (0, 4) applies to variable controls for the for loop

To: range (0, 4)

3. String

Original: String is stored as an 8-bit string

Instead: Strings are stored as 16-bit Unicode strings

Try except statements

The original: try:

. except Exception, e : ......Copy the code

Instead of

try:

      ......

 except    Exception as e :

     ......
Copy the code

Open the file

Original: file(…..)

Or open (...).Copy the code

To:

Can only use the open (...).Copy the code

Type a string from the keyboard

Original: raw_input(” prompt “)

Change to: input(” prompt “)

Bytes data type

A bytes object is an immutable array. The items are 8-bit bytes, represented by integers in the range 0 <= x < 256.

Bytes can be thought of as a byte array object. Each element is an 8-bit byte. The value ranges from 0 to 255.

Because strings are stored in Unicode encoding in Python 3.0, strings cannot be written (or read) directly when written to binaries and must be encoded in some way as a sequence of bytes before they can be written.

(1) String encoding (encode) is bytes

Example: s = “Zhang SAN abc12”

B = s.encode() # b = s.encode() # b = s.encode() # An exception is thrown when the string cannot be encoded to the specified encoding modeCopy the code

(2) Decode bytes as a string

S = "abc12" b = S.encode (" GBK ") # string s encoded in GBK format s1 = B.decode (" GBK ") # decode b in GBK format as string # description, An exception is thrown when a byte sequence cannot be decoded in the specified encoding formatCopy the code

(3) Examples of usage methods

coding=gbk

F = open(“c:\1234. TXT “, “wb”) s = “abcd1234”

——————————-

In python2.4 we can write:

f.write( s )

Exceptions are thrown in Python 3.0

——————————-

b = s.encode(“gbk”)

f.write( b )

f.close()

input(“?” )

An example of reading this file:

coding=gbk

F = open(“c:\1234.txt”, “rb”) f = open(“c:\1234.txt”, “rb”) f = open(“c:\1234.txt”, “rb”) f = open(“c:\1234.txt”, “rb”) f = open(“c:\1234.txt”, “rb”) f = open(“c:\1234.txt”, “rb”) f = open(“c:\1234.txt”, “rb”) f = open

——————————

B is a string in Python 2.4

To python 3.0, b is of type bytes

Therefore, it is necessary to confirm the code according to the specified encoding mode

——————————

s = b.decode(“gbk”)

print ( s )

——————————

In Python 2.4 you can write print s or print (s)

In Python 3.0 you must write print (s)

——————————

f.close() input(“?” )

After running, it should display:

B c D 1234

(4) Bytes sequence, once formed, its content is immutable

Ex. :

s=”ABCD”

b=s.encode(“gbk”)

Print b[0] #

b[0] = 66

The ‘bytes’ object does not support item Assignment

CHR (K) and ORD (c)

Python 2.4.2 before

CHR (K) converts the encoding K to a character, which ranges from 0 to 255

Ord (c) Specifies the encoding of a single character. The returned value ranges from 0 to 255

Python 3.0

CHR (K) converts the code K to a character. The value of K ranges from 0 to 65535

Ord (c) Specifies the encoding of a single character. The returned value ranges from 0 to 65535

The division operator

Python 2.4.2 before

10/3 is equal to 3

Python 3.0

10/3 result is 3.33333333333335

10 over 3 is equal to 3

Byte array object — added

(1) Initialization

A = bytearray(10) # a = bytearray(10) # a = bytearray(10) # a = bytearray(10) # A = bytearray(10) # A = bytearray(10) #Copy the code

Byte arrays are mutable

A = byteArray (10) a[0] = 25 # You can use an assignment statement to change the element, but the assigned value must be between 0 and 255Copy the code

(3) A slice of a byte array is still a byte array

(4) String is converted into byte array

#coding= GBK s =" hello "b = s.encode(" GBK ") # Converting a string of bytes to a certain GBK encoding c = bytearray(b) # Converting bytes to an array of bytes can also be written as C = Bytearray (" Hello ", "GBK ")Copy the code

(5) Byte array to string

c = bytearray( 4 ) c[0] = 65 ; c[1]=66; c[2]= 67; C [3]= 68 s = c.decode(" GBK ") print (s) #Copy the code

Byte arrays can be used to write text files

coding=gbk

F = open(“c:\1234. TXT “, “wb”) s = “abcd1234”

——————————-

In python2.4 we can write:

f.write( s )

Exceptions are thrown in Python 3.0

——————————-

b = s.encode(“gbk”)

F word (b) c=bytearray(” 五”,” GBK “) F word (c) f word ()

input(“?” )

Interested persons can add QQ to communicate: 3271330538 white piao information please click 666