注:
來自 https://learnxinyminutes.com/docs/python3/ 和 http://learnxinyminutes.com/docs/python/
Python是Guido Van Rossum在90年代發(fā)明的兰英。它是目前最熱鬧的編程語言之一憔披。
原始數據類型與操作
數值型
# 數值型
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
# 如果只需要整數部分枣申,使用"http://"做除法,又叫地板除(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
# 使用括號改變優(yōu)先級
(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
# 可以使用切片句法訪問列表
# 這里類型數學上的開/閉區(qū)間
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
# 使用“l(fā)en()”來檢查列表的長度
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."
循環(huán)結構
# For 循環(huán)用來遍歷一個列表
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 循環(huán)會一致執(zhí)行下去,直到條件不滿足
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語句塊中沒有拋出異常才會執(zhí)行
finally: # 所有情況都會執(zhí)行
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" 來創(chuàng)建一個新的函數
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 創(chuàng)建一個子類
class Human(object):
# 一個類屬性,所有該類的實例都可以訪問
species = "H. sapiens"
# 基礎實例化方法家卖,在創(chuàng)建一個實例時調用
# 注意在名稱前后加雙下劃線表示對象或者屬性是 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
# 創(chuàng)建一個實例
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"
# 調用靜態(tài)方法
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/)