Difference between Python3.0 and 2.x, for example, python3.02.x

Source: Internet
Author: User

Difference between Python3.0 and 2.x, for example, python3.02.x

This article lists some common examples to analyze the differences between Python3.0 and 2.x, which is a summary of the author's experience and has good reference value for Python programmers. The details are as follows:

As A front-end developer, I recently read the latest version of A byte of Python and compared it with the old version of A byte of Python, it is found that Python3.0 has some changes in some places. Then, read the documents on the official website to summarize the differences:

1. If you download the latest Python version, you will find that the Hello World examples in all books are no longer correct.
The Python2.X code is as follows:

Print "Hello World! "# Print strings

The Python3.0 code is as follows:

print("Hello World!") 

Put the string in the brackets and print it out. This writing method is very friendly for me who are from Java ~ O (distinct _ distinct) O ~

2.
The Python2.X code is as follows:

Guess = int (raw_input ('enter an integer: ') # How to read keyboard input

The Python3.0 code is as follows:

guess = int(input('Enter an integer : ')) 

The method name becomes easier to remember!

3.
A new nonlocal statement is added, a non-local variable, which ranges between global and local and is mainly used for function nesting. Its usage is as follows:

#!/usr/bin/python # Filename: func_nonlocal.py def func_outer():   x = 2   print('x is', x)   def func_inner():     nonlocal x     x = 5   func_inner()   print('Changed local x to', x) func_outer() 

4.
VarArgs parameters. I don't know what to translate this? Let's take a look at the following example:

#!/usr/bin/python # Filename: total.py def total(initial=5, *numbers, **keywords):   count = initial   for number in numbers:     count += number   for key in keywords:     count += keywords[key]   return count print(total(10, 1, 2, 3, vegetables=50, fruits=100)) 

When * is used before a parameter, all location parameters (, 3) are passed as a list.
When the ** identifier is used before the parameter, all key parameters (vegetables = 50, fruits = 100) are passed as a dictionary.

5.
My personal understanding about Packages is limited. Interested readers can refer to relevant documents.

6.
In the data structure, there is one more type: set
Set is a set of unordered simple objects. When we care about whether an object exists in a Set, and the sequence and number of occurrences are secondary, we can use set.

7.
For the OS. sep method, set is the separator)
Let's take a look at the author's example:
The Python2.X code is as follows:

target_dir = '/mnt/e/backup/' target = target_dir + time.strftime('%Y%m%d%H%M%S') + '.zip' 

The Python3.0 code is as follows:

target_dir = 'E:\\Backup' target = target_dir + os.sep + time.strftime('%Y%m%d%H%M%S') + '.zip' 

OS. the function of sep is to automatically identify the operating system and provide different delimiters. It is \ on Windows and/on Linux. The principle is clear and the function is good, but the author's example is as follows. Only one OS. sep is used, and the rest is still written in the old way (E :\\)

8.
You can use the @ modifier to declare a class method:

  @classmethod   def howMany(klass):     '''Prints the current population.'''     print('We have {0:d} robots.'.format(Robot.population)) 

9.
You can declare a class as an abstract method in Metaclasses.

from abc import * class SchoolMember(metaclass=ABCMeta):   '''Represents any school member.'''   def __init__(self, name, age):     self.name = name     self.age = age     print('(Initialized SchoolMember: {0})'.format(self.name))   @abstractmethod   def tell(self):     '''Tell my details.''' print('Name:"{0}" Age:"{1}"'.format(self.name, self.age), end=" ")     #pass 

10.
The file read/write mode adds two more types: Text ('T') binary file ('B ').

11. put the operations to open a file in the method modified using the with statement. The advantage of the book is that we focus more on file operations and make the Code look messy, this article cannot fully understand the benefits of. The sample code is provided for your reference:

#!/usr/bin/python # Filename: using_with.py from contextlib import context @contextmanager def opened(filename, mode="r")   f = open(filename, mode)   try:     yield f   finally:     f.close() with opened("poem.txt") as f:   for line in f:     print(line, end='') 

12. The logging module is added to python3.0, which gives me the feeling that it is similar to the log4j in Java. Check the Code directly:

import os, platform, logging if platform.platform().startswith('Windows'): logging_file = os.path.join(os.getenv('HOMEDRIVE'), os.getenv('HOMEPATH'), 'test.log') else:   logging_file = os.path.join(os.getenv('HOME'), 'test.log') logging.basicConfig(   level=logging.DEBUG,   format='%(asctime)s : %(levelname)s : %(message)s',   filename = logging_file,   filemode = 'w', ) logging.debug("Start of the program") logging.info("Doing something") logging.warning("Dying now")

I hope this article will help you understand the usage of Python3.0 and Python2.X.


What is the essential difference between Python 2x and 3x?

It does not show 2.7 from 3.1, but from 2.6. 2.7 is a version released to smooth Python over 3. X. It includes some 3.x features. The main differences are: (for personal opinions, you can go to the official website to view their opinions)
Without the classic class, all are new classes, that is, the class object has no parent class, so it is inherited from the object;
Change print and exec from statement to function;
In addition, str is changed to unicode, which is equivalent to 2. unicode object of X, 2. change str of X to bytes (this is much more convenient, unlike 2. X if the encoding is incorrect, it is uncomfortable ).

What is the main difference between Python 25 and Python 30?

#1 if the print statement is absent, replace it with the print () function.
#2 the new str type indicates a Unicode string, which is equivalent to the unicode type of Python 2.x.
#3 division operator/always returns a floating point number in Python 3. x. In Python 2.6, the system checks whether the divisor and divisor are integers.
#4 the syntax for capturing exceptions is changed from syntax t exc and var to syntax t exc as var.
#5 new syntax for set: {1, 2, 3, 4 }. Note that {} still indicates an empty dictionary (dict)
# The number of 8 bytes must be written as 0o777. The original format 0777 cannot be used. The binary value must be written as 0b111.
#7 dict. keys (), dict. values (), dict. items (), map (), filter (), range (), zip () no longer returns the list, but the iterator
#8 if there is no clearly defined order between two objects. If you use <,>, <=,> = to compare them, an exception is thrown.
#9 comments can be made to function parameters and return values.
# Renamed more than 10 Modules
#11 The StringIO module is now merged into the new io module. New, md5, gopherlib, and other modules are deleted.
#12 httplib, BaseHTTPServer, CGIHTTPServer, SimpleHTTPServer, Cookie, and cookielib are merged into the http package.
#13 the exec statement is canceled, and only the exec () function is left.
Reference: docs.python.org/..0.html

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.