Learn Python in Y minutes

注:
来自 https://learnxinyminutes.com/docs/python3/http://learnxinyminutes.com/docs/python/

Python是Guido Van Rossum在90年代发明的。它是目前最热闹的编程语言之一。

原始数据类型与操作

数值型

# 数值型
3 # => 3

# 数学计算
1 + 1 # => 2
8 - 1 # => 7
10 * 2 # => 20
35 / 5 # => 7

# 整型(int)的除法只会获得整型结果,余数自动舍弃 Python 2.7
5 / 2 # => 2
# Python会自动返回浮点数
5 / 2 # => 2.5

# 浮点型(float)的计算可以有小数
2.0 # 这是一个浮点型
11.0 / 4.0 # => 2.75

# 如果只需要整数部分,使用"//"做除法,又叫地板除(foored division)
5 // 3 # => 1
5.0 // 3.0 # => 1.0 浮点型效果也一样
-5 // 3 # => -2
-5.0 // 3.0 # => -2.0

# 取余操作
7 % 3 # => 1

# 幂操作
2 ** 4 # => 16

# 使用括号改变优先级
(1+3) * 2 # => 8

布尔型

# 注: "and" 和 "or" 都是大小写敏感的
True and False # => False
False or True # => True

# 注:int型也可以使用布尔操作
0 and 2 # => 0
-5 or 0 # => -5
0 == False # => True
2 == True # => False
1 == True # => True

# 非操作
not True # => False
not False # => True

# 判断相等
1 == 1 # => True
2 == 1 # => False

# 判断不相等
1 != 1 # => False
2 != 1 # => True

# 其它比较操作
1 < 10 # => True
1 > 10 # => False
2 <= 2 # => True
2 >= 2 # => True

# 比较操作可以串联
1 < 2 < 3 # => True
1 < 3 < 2 # => False

# is 与 == 比较
# is 是判断两个变量是否引用了同一个类
# == 是判断两个变量是否有同样的值
a = [1, 2, 3, 4]  # 将 a 指向一个新的数组 [1, 2, 3, 4]
b = a             # 将 b 指向 a 所指向的对象
b is a            # => True, a 和 b 引用了同一个对象
b == a            # => True, a 和 b 的对象值也相同
b = [1, 2, 3, 4]  # 将 b 指向一个新的数组 [1, 2, 3, 4]
b is a            # => False, a 和 b 不是引用了同一个对象
b == a            # => True, a 和 b 的对象值相同

字符串

# 字符串使用 单引号 或者 双引号 表示
"这是一个字符串"
'这也是一个字符串'

# 字符串可以使用"+"连接
"Hello " + "world!" # "Hello world!"
# 不使用"+"也可以让字符串连接
"Hello " "world!" # "Hello world!"

# 字符串乘法
"Hello" * 3 # => "HelloHelloHello"

# 字符串可以当作字符数组操作
"This is a string"[0] # => "T"

# 使用 % 对字符串进行格式化
# 从Python 3.1 开始已经不推荐使用了,但了解一下如何使用还是有必要的
x = 'apple'
y = 'lemon'
z = "The items in the basket are %s and %s " % (x,y)

# 新的格式化字符串的方式是使用format方法
"{} is a {}".format("This", "placeholder")
"{0} can be {1}".format("strings", "formatted")
# 如果不想用下标方式,可以使用关键字的方式
"{name} wants to eat {food}".format(name="Bob", food="lasagna")

其它

# None 是一个对象
None # => None

# 如果想要将一个对象与None进行比较,使用 is 而不要使用 == 符号
"etc" is None # => False
None is None # => True

# is 操作用来判断对象的类型。在对象操作时非常有用

# 任何一个对象都可以放在一个布尔上下文中进行判断
# 下面的情况会被当作False
#   - None
#   - 值为0的任何数值类型,(例如,0,0L,0.0,0j)
#   - 空列表,(例如,'',(),[])
#   - 空的容器,(例如,{},set())
#   - 符合条件的用户自定义对象实例,参看:https://docs.python.org/2/reference/datamodel.html#object.__nonzero__
#
# 其它情况下的值会被当作True,可以使用bool()函数来判断
bool(0)   # => False
bool("")  # => False
bool([])  # => False
bool({})  # => False

变量与集合

输入输出

# Python有一个打印语句
print "I'm Python. Nice to meet you!" # => I'm Python. Nice to meet you!

# 获取控制台输入的简单方法
input_string_var = raw_input("Enter some data: ") # 返回字符串类型的数据
input_var = input("Enter some data: ") # 返回数值型的数据
# Warning: Caution is recommended for input() method usage
# 注意:在Python3中,input()已经不再使用,raw_input()重命名为input()

# 不需要先声明变量再使用
some_var = 5    # 通常使用小写字母与下划线命名变量
some_var  # => 5

# 访问一个未定义的变量会抛出一个异常
# 在“控制流”里会介绍更多异常处理
some_other_var  # 这里会抛出一个NameError

# if 可以用来写成类似C语言的 '?:' 条件表达式
"yahoo!" if 3 > 2 else 2  # => "yahoo!"

列表(List)

# List用来存储列表
li = []
# 可以有初始数据
other_li = [4, 5, 6]

# 添加元素到列表的尾
li.append(1) # [1]
li.append(2) # [1,2]
li.append(4) # [1,2,4]
li.append(3) # [1,2,4,3]
# 使用pop方法移除列表末尾的元素
li.pop()        # => 3 列表现在为 [1, 2, 4]
# 把3再放回去
li.append(3)    # li 现在为 [1, 2, 4, 3]

# 像数组一样访问一个list
li[0]  # => 1
# 通过下标重新定义一个元素的值
li[0] = 42
li[0]  # => 42
li[0] = 1  # 注意:设置回原始值
# 查看最后一个元素
li[-1]  # => 3

# 查找超过数据长度的值会抛出异常: IndexError
li[4]  # 抛出 IndexError

# 可以使用切片句法访问列表
# 这里类型数学上的开/闭区间
li[1:3]  # => [2, 4]
li[2:]  # => [4, 3]
li[:3]  # => [1, 2, 4]
li[::2]   # =>[1, 4]
li[::-1]   # => [3, 4, 2, 1]
# 使用高级切片句法
# li[start:end:step]

# 使用切片进行深层拷贝
li2 = li[:]  # => li2 = [1, 2, 4, 3] 但 (li2 is li) 返回 false


# 使用“del”直接从列表中删除元素
del li[2] #liisnow[1,2,3]

# 可以直接添加一个列表
li+other_li #=>[1,2,3,4,5,6]
# 注: 变量li 和 other_li 值并没有变化

# 使用extend()方法,把列表串起来
li.extend(other_li)   # Now li is [1, 2, 3, 4, 5, 6]

# 删除第一个值与参数相同的元素
li.remove(2)  # li is now [1, 3, 4, 5, 6]
li.remove(2)  # 抛出异常 ValueError 列表中没有2

# 在指定下标插入元素
li.insert(1, 2)  # li is now [1, 2, 3, 4, 5, 6] again

# 获得第一个匹配的元素的下标
li.index(2)  # => 1
li.index(7)  # 抛出异常 ValueError 列表中没有7

# 使用“in”来检查列表中是否包含元素
1 in li #=>True
# 使用“len()”来检查列表的长度
len(li)   # => 6

元组(Tuple)

# 元组(Tuple)与列表类似但不可修改
tup = (1, 2, 3)
tup[0]   # => 1
tup[0] = 3  # 抛出异常 TypeError

# 注意:如果一个元组里只有一个元素,则需要在元素之后加一个逗号;如果元组里没有元素,反而不用加逗号
type((1))   # => <class 'int'>
type((1,))  # => <class 'tuple'>
type(())    # => <class 'tuple'>

# 以下对列表的操作,也可以用在元组上
len(tup) # => 3
tup+(4,5,6) #=>(1,2,3,4,5,6)
tup[:2] #=>(1,2)
2intup #=>True

# 可以把元组的值分解到多个变量上
a,b,c= (1, 2, 3) #a is now 1,b  is now 2 and c is now 3
d,e,f= 4,5,6 # 也可以不带括号
# 如果不带括号,元组会默认带上
g = 4, 5, 6 #=>(4,5,6)
# 非常容易实现交换两个变量的值
e, d = d, e # d is now 5 and e is now 4

字典(Dictionaries)

# 字典用来存储(键-值)映射关系
empty_dict = {}
# 这里有个带初始值的字典
filled_dict = {"one": 1, "two": 2, "three": 3}

# 注意:字典 key 必须是不可以修改类型,以确保键值可以被哈希后进行快速检索
# 不可修改的类型包括:int, float, string, tuple
invalid_dict = {[1,2,3]: "123"}  # => Raises a TypeError: unhashable type: 'list'
valid_dict = {(1,2,3):[1,2,3]}   # Values can be of any type, however.

# 使用[]查找一个元素
filled_dict["one"]   # => 1
# 使用"keys()"获得所有的“键”
filled_dict.keys()   # => ["three", "two", "one"]
# 注:字典的key是无序的,结果可以不匹配
# 使用"values()"获得所有的“值”
filled_dict.values()   # => [3, 2, 1]
# 注:同样,这是无序的
# 查询字条中是否存在某个”键“用 "in"
"one" in filled_dict   # => True
1 in filled_dict   # => False
# 查找一个不存在的key会抛出异常 KeyError
filled_dict["four"]   # KeyError
# 使用 "get()" 会避免抛出异常 KeyError
filled_dict.get("one") # => 1
filled_dict.get("four") # => None
# get方法支持默认参数,当key不存在时返回该默认参数
filled_dict.get("one", 4) #=>1
filled_dict.get("four", 4)   # => 4
# 注 filled_dict.get("four") 仍然返回 None
# (get不会把值插入字典中)
# 向字典中插入值的方式与list相同
filled_dict["four"] = 4  # now, filled_dict["four"] => 4
# "setdefault()" 只有首次插入时才会生效
filled_dict.setdefault("five", 5)  # filled_dict["five"] is set to 5
filled_dict.setdefault("five", 6)  # filled_dict["five"] is still 5

# 使用 del 从字典中删除一个键
del filled_dict["one"]  # Removes the key "one" from filled dict

# 从 Python 3.5 开始,可以使用**操作
{'a': 1, **{'b': 2}}  # => {'a': 1, 'b': 2}
{'a': 1, **{'a': 2}}  # => {'a': 2}

集合(Set)

# Set与list类似,但不存储重复的元素
empty_set = set()
some_set = set([1, 2, 2, 3, 4])   # some_set is now set([1, 2, 3, 4])

# 与字典类型一样,Set 里的元素也必须是不可修改的
invalid_set = {[1], 1}  # => Raises a TypeError: unhashable type: 'list'
valid_set = {(1,), 1}

# Set也是无序的,尽管有时看上去像有序的
another_set = set([4, 3, 2, 2, 1])  # another_set is now set([1, 2, 3, 4])
# 从Python 2.7开妈, {}可以用来声明一个Set
filled_set={1,2,2,3,4} #=>{1,2,3,4}
# Can set new variables to a set
filled_set = some_set
# 向Set中添加元素
filled_set.add(5)   # filled_set is now {1, 2, 3, 4, 5}
# 用 & 求 Set的交集
other_set = {3, 4, 5, 6}
filled_set & other_set # =>{3,4,5}
# 用 | 求 Set的合集
filled_set | other_set # =>{1,2,3,4,5,6}
# Do set difference with - 
{1,2,3,4}-{2,3,5} # => {1,4}
# Do set symmetric difference with ^ 
{1,2,3,4}^{2,3,5} #=>{1,4,5}
# 检查右边是否是左边的子集
{1, 2} >= {1, 2, 3} # => False
# 检查左边是否是右边的子集
{1, 2} <= {1, 2, 3} # => True
# 检查元素是否在集合中
2 in filled_set   # => True
10 in filled_set   # => False

控制流

分支结构

# 先定义一个变量
some_var = 5
# 这里用到了if语句 缩进是Python里的重要属性
# 打印 "some_var is smaller than 10"
if some_var > 10:
    print "some_var is totally bigger than 10."
elif some_var < 10:    # This elif clause is optional.
    print "some_var is smaller than 10."
else:           # This is optional too.
    print "some_var is indeed 10."

循环结构

# For 循环用来遍历一个列表
for animal in ["dog", "cat", "mouse"]:
    # 使用{0}格式 插入字符串
    print "{0} is a mammal".format(animal)

# "range(number)" 返回一个包含数字的列表
for i in range(4):
print i

# "range(lower, upper)" 返回一个从lower数值到upper数值的列表
for i in range(4, 8):
print i

# "range(lower, upper, step)" 返回一个从lower数值到upper步长为step数值的列表
# step 的默认值为1
for i in range(4, 8, 2):
    print(i)
# While 循环会一致执行下去,直到条件不满足
x=0
while x < 4:
print x
x+=1 #x=x+1的简写

异常处理

# 使用 try/except 代码块来处理异常
# 自 Python 2.6 以上版本支持:
try:
    # 使用 "raise" 来抛出一个异常
    raise IndexError("This is an index error")
except IndexError as e:
    pass    # Pass 表示无操作. 通常这里需要解决异常.
except (TypeError, NameError):
    pass    # 如果需要多个异常可以同时捕获
else:   # 可选项. 必须在所有的except之后
    print "All good!"   # 当try语句块中没有抛出异常才会执行
finally: #  所有情况都会执行
    print "We can clean up resources here"

# with 语句用来替代 try/finally 简化代码
with open("myfile.txt") as f:
    for line in f:
        print line

迭代器

# Python offers a fundamental abstraction called the Iterable.
# An iterable is an object that can be treated as a sequence.
# The object returned the range function, is an iterable.

filled_dict = {"one": 1, "two": 2, "three": 3}
our_iterable = filled_dict.keys()
print(our_iterable)  # => dict_keys(['one', 'two', 'three']). This is an object that implements our Iterable interface.

# We can loop over it.
for i in our_iterable:
    print(i)  # Prints one, two, three

# However we cannot address elements by index.
our_iterable[1]  # Raises a TypeError

# An iterable is an object that knows how to create an iterator.
our_iterator = iter(our_iterable)

# Our iterator is an object that can remember the state as we traverse through it.
# We get the next object with "next()".
next(our_iterator)  # => "one"

# It maintains state as we iterate.
next(our_iterator)  # => "two"
next(our_iterator)  # => "three"

# After the iterator has returned all of its data, it gives you a StopIterator Exception
next(our_iterator)  # Raises StopIteration

# You can grab all the elements of an iterator by calling list() on it.
list(filled_dict.keys())  # => Returns ["one", "two", "three"]

函数

# 使用 "def" 来创建一个新的函数
def add(x, y):
    print "x is {0} and y is {1}".format(x, y)
    return x + y    # 用 return 语句返回值
# 调用函数
add(5,6) #=>prints out "x is 5 and y is 6" 返回值为11
# 使用关键字参数调用函数
add(y=6, x=5)   # 关键字参数可以不在乎参数的顺序
# 函数的参数个数可以不定,使用*号会将参数当作元组
def varargs(*args):
    return args
varargs(1, 2, 3)   # => (1, 2, 3)

# 也可以使用**号将参数当作字典类型
def keyword_args(**kwargs):
    return kwargs
  # 调用一下试试看
keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"}

# 两种类型的参数可以同时使用
def all_the_args(*args, **kwargs):
    print args
    print kwargs
"""
all_the_args(1, 2, a=3, b=4) prints:
    (1, 2)
    {"a": 3, "b": 4}
"""

# When calling functions, you can do the opposite of args/kwargs!
# Use * to expand positional args and use ** to expand keyword args.
args = (1, 2, 3, 4)
kwargs = {"a": 3, "b": 4}
all_the_args(*args)   # 相当于 foo(1, 2, 3, 4)
all_the_args(**kwargs)   # 相当于 foo(a=3, b=4)
all_the_args(*args, **kwargs)   # 相当于 foo(1, 2, 3, 4, a=3, b=4)
# you can pass args and kwargs along to other functions that take args/kwargs
# by expanding them with * and ** respectively
def pass_all_the_args(*args, **kwargs):
    all_the_args(*args, **kwargs)
    print varargs(*args)
    print keyword_args(**kwargs)

# Returning multiple values (with tuple assignments)
def swap(x, y):
    return y, x  # Return multiple values as a tuple without the parenthesis.
                 # (Note: parenthesis have been excluded but can be included)

x = 1
y = 2
x, y = swap(x, y)     # => x = 2, y = 1
# (x, y) = swap(x,y)  # Again parenthesis have been excluded but can be included.

函数的作用域

x=5
def set_x(num):
    # 局部变量x与全局变量x不相同
    x = num # => 43
    print x # => 43
def set_global_x(num):
    global x
    print x # => 5
    x = num # 全局变量被设置成为6
    print x # => 6
set_x(43)
set_global_x(6)
# 函数也可以是对象
def create_adder(x):
    def adder(y):
        return x + y
return adder
add_10 = create_adder(10)
add_10(3)   # => 13
# 匿名函数
(lambda x: x > 2)(3)   # => True
(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5
# 高阶函数
map(add_10, [1, 2, 3])   # => [11, 12, 13]
map(max, [1, 2, 3], [4, 2, 1])   # => [4, 2, 3]
filter(lambda x: x > 5, [3, 4, 5, 6, 7])   # => [6, 7]
# We can use list comprehensions for nice maps and filters
[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13]
[x for x in[3,4,5,6,7] if x>5] #=>[6,7]

# 继承 object 创建一个子类
class Human(object):
    # 一个类属性,所有该类的实例都可以访问
    species = "H. sapiens"
    # 基础实例化方法,在创建一个实例时调用
    # 注意在名称前后加双下划线表示对象或者属性是 Python 的特殊用法,但用户可以自己控制
    # 最好不要在自己的方法前这样使用
    def __init__(self, name):
        # 将参数赋值给实例属性
        self.name = name
        # 初始化属性
        self.age = 0
    # 一个实例方法。所有实例方法的第一个属性都是self
    def say(self, msg):
        return "{0}: {1}".format(self.name, msg)

    # A class method is shared among all instances
    # They are called with the calling class as the first argument
    @classmethod
    def get_species(cls):
        return cls.species 

    # A static method is called without a class or instance reference
    @staticmethod
    def grunt():
        return "*grunt*"

    # A property is just like a getter.
    # It turns the method age() into an read-only attribute
    # of the same name.
    @property
    def age(self):
        return self._age

    # This allows the property to be set
    @age.setter
    def age(self, age):
        self._age = age

    # This allows the property to be deleted
    @age.deleter
    def age(self):
        del self._age

# 创建一个实例
i = Human(name="Ian")
print i.say("hi") # prints out "Ian: hi"

j = Human("Joel")
print j.say("hello")  # prints out "Joel: hello"

# 调用类方法
i.get_species()   # => "H. sapiens"

# 访问共有变量
Human.species = "H. neanderthalensis"
i.get_species()   # => "H. neanderthalensis"
j.get_species()   # => "H. neanderthalensis"

# 调用静态方法
Human.grunt()   # => "*grunt*"

# Update the property
i.age = 42

# Get the property
i.age # => 42

# Delete the property
del i.age
i.age  # => raises an AttributeError

模块

# 可以直接引用其它模块
import math
print math.sqrt(16)  # => 4
# 也可以引用模块中的函数
from math import ceil, floor
print ceil(3.7)  # => 4.0
print floor(3.7)   # => 3.0

# 你可以引用一个模块中的所有函数
# 警告:这是不推荐的
from math import *
# 可以给模块起个简短的别名
import math as m
math.sqrt(16) == m.sqrt(16)   # => True
# you can also test that the functions are equivalent
from math import sqrt
math.sqrt == m.sqrt == sqrt  # => True
# Python modules are just ordinary python files. You
# can write your own, and import them. The name of the
# module is the same as the name of the file.
# You can find out which functions and attributes
# defines a module.
import math
dir(math)

高级

# Generators help you make lazy code
def double_numbers(iterable):
    for i in iterable:
        yield i + i
# A generator creates values on the fly.
# Instead of generating and returning all values at once it creates one in each
# iteration.  This means values bigger than 15 wont be processed in
# double_numbers.
# Note xrange is a generator that does the same thing range does.
# Creating a list 1-900000000 would take lot of time and space to be made.
# xrange creates an xrange generator object instead of creating the entire list
# like range does.
# We use a trailing underscore in variable names when we want to use a name that
# would normally collide with a python keyword
xrange_ = xrange(1, 900000000)
# will double all numbers until a result >=30 found
for i in double_numbers(xrange_):
    print i
    if i >= 30:
break 
# Decorators
# in this example beg wraps say
# Beg will call say. If say_please is True then it will change the returned
# message
from functools import wraps

def beg(target_function):
    @wraps(target_function)
    def wrapper(*args, **kwargs):
        msg, say_please = target_function(*args, **kwargs)
        if say_please:
            return "{} {}".format(msg, "Please! I am poor :(")
        return msg
    return wrapper
@beg
def say(say_please=False):
    msg = "Can you buy me a beer?"
    return msg, say_please
print say()  # Can you buy me a beer?
print say(say_please=True)  # Can you buy me a beer? Please! I am poor :(

Free Online

Automate the Boring Stuff with Python (https://automatetheboringstuff.com)

Learn Python The Hard Way (http://learnpythonthehardway.org/book/)

Dive Into Python (http://www.diveintopython.net/)

Ideas for Python Projects(http://pythonpracticeprojects.com/)

The Official Docs (http://docs.python.org/2/)

Hitchhiker’s Guide to Python (http://docs.python-guide.org/en/latest/)

Python Module of the Week (http://pymotw.com/2/)

Python Course(http://www.python-course.eu/index.php)

First Steps With Python(https://realpython.com/learn/python-first-steps/)

A Crash Course in Python for Scientists (http://nbviewer.ipython.org/5920182)

First Steps With Python (https://realpython.com/learn/python-first-steps/)

Fullstack Python (https://www.fullstackpython.com/)

30Python Language Features and Tricks You May Not Know About(http://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html)

Official Style Guide for Python(https://www.python.org/dev/peps/pep-0008/)

Python 3 Computer Science Circles(http://cscircles.cemc.uwaterloo.ca/)

推荐阅读更多精彩内容