Python2 vs. Python3

Posted by Ollie on January 7, 2017

Ch0—探索学习节奏

1. Python2 vs. Python3

版本差异简述

  • 最新的更新默认只在 py3 中可用。
  • py3 不向下兼容。
  • py3 对 unicode 有更好的支持,默认使用utf-8(之前尝试使用lxml读取网页信息时,py2 中文字符输出为unicode编码,要再转换;py3 可直接输出为中文字符)。
  • py3 语言一致性更强,对初学者更友好(例如:print、exec 语句改为函数print()、exec();xrange()被range()替代;整数相除,保留小数部分,可以是浮点数等)。

具体差异整理的参考链接:

(除了函数的改变其他改变大部分没看懂……先放上链接,任务中遇到困难再去解决)

如何选择版本?

  优势 劣势
Py3   1.有的库支持略差;2. 部分 Linux,Macs 默认py2
Py2 1.兼容更多的包;  

所以当操作环境不可改变,只能使用 py2,以及使用的 package 不支持 py3 时,选择 py2。

  • Py3 支持较好的主要 package:
用图 package
数字处理与科学计算 NumPy,SciPy
网站 Django, Flask, CherryPy and Pyramid
图像处理 PIL(was superseded by its fork Pillow)
应用程序打包 cx_Freeze
应用程序打包(Windows) py2exe
开放源代码视觉处理与机器学习 OpenCV 3
HTTP Requests
XML lxml
HTML,XML 解析 BeautifulSoup4
交互计算环境 IPython/Jupyter
  • 只能在 Py3 应用的特征的不完全清单(很多意义不明,所以不做翻译,先留下):

    • strings are Unicode by default
    • clean Unicode/bytes separation
    • exception chaining
    • function annotations
    • syntax for keyword-only arguments
    • extended tuple unpacking
    • non-local variable declarations

如何同时兼容 py2/3

2. 夯实 Python 基础

  • 80% Python 的常用场景

从 LPTHW 选取 7 个练习,用 py3.x 改写,包括了上面提到的80%的常用场景以及类和对象,分别是:

  • 练习3:数字与数字计算
  • 练习6:变量、字符串、文本与打印
  • 练习17:提示、输入与文件操作
  • 练习24:函数综合练习
  • 练习35:if 语句、循环、列表综合练习
  • 练习39:列表与字典
  • 练习42:物以类聚(对象、类、从属关系)

练习3:数字与数字计算

  • print 更改为 print()
print("I will now count my chickens:")
print("Hens", 25 + 30 / 6) # py2结果为30
print("Roosters", 100 - 25 * 3 % 4)

print("Now I will count the eggs:")
print(3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6)  py2结果为整数

print("Is it true that 3 + 2 < 5 - 7?")
print(3 + 2 < 5 - 7)

print("What is 3 + 2?", 3 + 2)
print("What is 5 - 7?", 5 - 7)

print("Oh, that's why it's False.")

print("How about some more.")

print("Is it greater?", 5 > -2)
print("Is it greater or equal?", 5 >= -2)
print("Is it less or equal?", 5 <= -2)
I will now count my chickens:
Hens 30.0
Roosters 97
Now I will count the eggs:
6.75
Is it true that 3 + 2 < 5 - 7?
False
What is 3 + 2? 5
What is 5 - 7? -2
Oh, that's why it's False.
How about some more.
Is it greater? True
Is it greater or equal? True
Is it less or equal? False

练习6:变量、字符串、文本与打印

x = "There are %d types of people." % 10
binary = "binary"
do_not = "don't"
y = "Those who know %s and those who %s." % (binary, do_not)

print(x)
print(y)

print("I said: %r." % x)
print("I also said: '%s'." % y)

hilarious = False
joke_evaluation = "Isn't that joke so funny?! %r"

print(joke_evaluation % hilarious)

w = "This is the left side of..."
e = "a string with a right side."

print(w + e)
There are 10 types of people.
Those who know binary and those who don't.
I said: 'There are 10 types of people.'.
I also said: 'Those who know binary and those who don't.'.
Isn't that joke so funny?! False
This is the left side of...a string with a right side.

练习17:提示、输入与文件操作

from sys import argv
from os.path import exists

script, from_file, to_file = argv

print("Copying from %s to %s" % (from_file, to_file))

in_file = open(from_file)
indata = in_file.read()

print("The input file is %d bytes long" % len(indata))

print("Does the output file exist? %r" % exists(to_file))
print("Ready, hit RETURN to continue, CTRL-C to abort.")
raw_input()

out_file = open(to_file, 'w')
out_file.write(indata)

print("Alright, all done.")

out_file.close()
in_file.close()
Copying from -f to /Users/lixin/Library/Jupyter/runtime/kernel-9433043b-c72c-45ea-a85e-5feb7f59dc62.json



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

FileNotFoundError                         Traceback (most recent call last)

<ipython-input-3-a30bf329e718> in <module>()
      7 
      8 # we could do these two on one line, how?
----> 9 in_file = open(from_file)
     10 indata = in_file.read()
     11 


FileNotFoundError: [Errno 2] No such file or directory: '-f'
!echo "This is a test file." > test.txt
!cat test.txt
This is a test file.
%run ex17.py test.txt new_file.txt
Copying from test.txt to new_file.txt
The input file is 21 bytes long
Does the output file exist? False
Ready, hit RETURN to continue, CTRL-C to abort.



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

NameError                                 Traceback (most recent call last)

/Users/lixin/Documents/Py103/Chap0/note/ex17.py in <module>()
     14 print("Does the output file exist? %r" % exists(to_file))
     15 print("Ready, hit RETURN to continue, CTRL-C to abort.")
---> 16 raw_input()
     17 
     18 out_file = open(to_file, 'w')


NameError: name 'raw_input' is not defined
  • raw_input() 改为 input()
%run ex17.py test.txt new_file.txt
Copying from test.txt to new_file.txt
The input file is 21 bytes long
Does the output file exist? False
Ready, hit RETURN to continue, CTRL-C to abort.
Alright, all done.

练习24:函数综合练习

print("Let's practice everything.")
print('You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs.')

poem = """
\tThe lovely world
with logic so firmly planted
cannot discern \n the needs of love
nor comprehend passion from intuition
and requires an explanation
\n\t\twhere there is none.
"""

print("--------------")
print(poem)
print("--------------")


five = 10 - 2 + 3 - 6
print("This should be five: %s" % five)

def secret_formula(started):
    jelly_beans = started * 500
    jars = jelly_beans / 1000
    crates = jars / 100
    return jelly_beans, jars, crates


start_point = 10000
beans, jars, crates = secret_formula(start_point)

print("With a starting point of: %d" % start_point)
print("We'd have %d beans, %d jars, and %d crates." % (beans, jars, crates))

start_point = start_point / 10

print("We can also do that this way:")
print("We'd have %d beans, %d jars, and %d crates." % secret_formula(start_point))
Let's practice everything.
You'd need to know 'bout escapes with \ that do 
 newlines and 	 tabs.
--------------

	The lovely world
with logic so firmly planted
cannot discern 
 the needs of love
nor comprehend passion from intuition
and requires an explanation

		where there is none.

--------------
This should be five: 5
With a starting point of: 10000
We'd have 5000000 beans, 5000 jars, and 50 crates.
We can also do that this way:
We'd have 500000 beans, 500 jars, and 5 crates.

练习35:if 语句、循环、列表综合练习

from sys import exit

def gold_room():
    print("This room is full of gold.  How much do you take?")

    choice = input("> ")
    if "0" in choice or "1" in choice:
        how_much = int(choice)
    else:
        dead("Man, learn to type a number.")

    if how_much < 50:
        print("Nice, you're not greedy, you win!")
        exit(0)
    else:
        dead("You greedy bastard!")


def bear_room():
    print("There is a bear here.")
    print("The bear has a bunch of honey.")
    print("The fat bear is in front of another door.")
    print("How are you going to move the bear?")
    bear_moved = False

    while True:
        choice = input("> ")

        if choice == "take honey":
            dead("The bear looks at you then slaps your face off.")
        elif choice == "taunt bear" and not bear_moved:
            print("The bear has moved from the door. You can go through it now.")
            bear_moved = True
        elif choice == "taunt bear" and bear_moved:
            dead("The bear gets pissed off and chews your leg off.")
        elif choice == "open door" and bear_moved:
            gold_room()
        else:
            print("I got no idea what that means.")


def cthulhu_room():
    print("Here you see the great evil Cthulhu.")
    print("He, it, whatever stares at you and you go insane.")
    print("Do you flee for your life or eat your head?")

    choice = input("> ")

    if "flee" in choice:
        start()
    elif "head" in choice:
        dead("Well that was tasty!")
    else:
        cthulhu_room()


def dead(why):
    print(why, "Good job!")
    exit(0)

def start():
    print("You are in a dark room.")
    print("There is a door to your right and left.")
    print("Which one do you take?")

    choice = input("> ")

    if choice == "left":
        bear_room()
    elif choice == "right":
        cthulhu_room()
    else:
        dead("You stumble around the room until you starve.")


start()
You are in a dark room.
There is a door to your right and left.
Which one do you take?
> left
There is a bear here.
The bear has a bunch of honey.
The fat bear is in front of another door.
How are you going to move the bear?
> take honey
The bear looks at you then slaps your face off. Good job!



An exception has occurred, use %tb to see the full traceback.


SystemExit: 0



/Users/lixin/anaconda/lib/python3.5/site-packages/IPython/core/interactiveshell.py:2889: UserWarning: To exit: use 'exit', 'quit', or Ctrl-D.
  warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)

练习39:列表与字典

states = {
    'Oregon': 'OR',
    'Florida': 'FL',
    'California': 'CA',
    'New York': 'NY',
    'Michigan': 'MI'
}

cities = {
    'CA': 'San Francisco',
    'MI': 'Detroit',
    'FL': 'Jacksonville'
}

cities['NY'] = 'New York'
cities['OR'] = 'Portland'

print('-' * 10)
print("NY State has: ", cities['NY'])
print("OR State has: ", cities['OR'])

print('-' * 10)
print("Michigan's abbreviation is: ", states['Michigan'])
print("Florida's abbreviation is: ", states['Florida'])

print('-' * 10)
print("Michigan has: ", cities[states['Michigan']])
print("Florida has: ", cities[states['Florida']])

print('-' * 10)
for state, abbrev in states.items():
    print("%s is abbreviated %s" % (state, abbrev))

print('-' * 10)
for abbrev, city in cities.items():
    print("%s has the city %s" % (abbrev, city))

print('-' * 10)
for state, abbrev in states.items():
    print("%s state is abbreviated %s and has city %s" % (
        state, abbrev, cities[abbrev]))

print('-' * 10)
state = states.get('Texas')

if not state:
    print("Sorry, no Texas.")

city = cities.get('TX', 'Does Not Exist')
print("The city for the state 'TX' is: %s" % city)
----------
NY State has:  New York
OR State has:  Portland
----------
Michigan's abbreviation is:  MI
Florida's abbreviation is:  FL
----------
Michigan has:  Detroit
Florida has:  Jacksonville
----------
Oregon is abbreviated OR
New York is abbreviated NY
Florida is abbreviated FL
California is abbreviated CA
Michigan is abbreviated MI
----------
FL has the city Jacksonville
CA has the city San Francisco
NY has the city New York
OR has the city Portland
MI has the city Detroit
----------
Oregon state is abbreviated OR and has city Portland
New York state is abbreviated NY and has city New York
Florida state is abbreviated FL and has city Jacksonville
California state is abbreviated CA and has city San Francisco
Michigan state is abbreviated MI and has city Detroit
----------
Sorry, no Texas.
The city for the state 'TX' is: Does Not Exist

练习42:物以类聚(对象、类、从属关系)

class Animal(object): 
    pass

class Dog(Animal):
    def __init__(self, name):
        self.name = name

class Cat(Animal):
    def __init__(self, name):
        self.name = name

class Person(object):
    def __init__(self, name):
        self.name = name
        self.pet = None

class Employee(Person):
    def __init__(self, name, salary):
        super(Employee, self).__init__(name) # 初始化name为父类的name
        self.salary = salary

class Fish(object):
    pass

class Salmon(Fish):
    pass

class Halibut(Fish):
    pass


rover = Dog("Rover")
satan = Cat("Satan")
mary = Person("Mary")
mary.pet = satan
frank = Employee("Frank", 120000)
frank.pet = rover
flipper = Fish()
crouse = Salmon()
harry = Halibut()

3. CLI

CLI 笔记

4. Gitbook

配置 GitBook 简易指南


Creative Commons License
This work is licensed under a CC A-S 4.0 International License.