用了好幾年python,發現還是有個別語法沒用到,比如 a,b=b,a 比如@classmethod 比如 dict.get(“x”, 1) 比如dict.setdefaults()。本文沒有提到yield語法。
Get the code: learnpython-zh.py
Python 由 Guido Van Rossum 在90年代初創建。 它現在是最流行的語言之一 我喜愛python是因爲它有極爲清晰的語法,甚至可以說,它就是可以執行的僞代碼
很歡迎來自您的反饋,你可以在@louiedinh 和 louiedinh [at] [google’s email service] 這裏找到我
注意: 這篇文章針對的版本是Python 2.7,但大多也可使用於其他Python 2的版本 如果是Python 3,請在網絡上尋找其他教程
# 單行註釋 """ 多行字符串可以用 三個引號包裹,不過這也可以被當做 多行註釋 """ #################################################### ## 1. 原始數據類型和操作符 #################################################### # 數字類型 3 # => 3 # 簡單的算數 1 + 1 # => 2 8 - 1 # => 7 10 * 2 # => 20 35 / 5 # => 7 # 整數的除法會自動取整 5 / 2 # => 2 # 要做精確的除法,我們需要引入浮點數 2.0 # 浮點數 11.0 / 4.0 # => 2.75 精確多了 # 括號具有最高優先級 (1 + 3) * 2 # => 8 # 布爾值也是基本的數據類型 True False # 用 not 來取非 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 2 < 3 < 2 # => False # 字符串通過 " 或 ' 括起來 "This is a string." 'This is also a string.' # 字符串通過加號拼接 "Hello " + "world!" # => "Hello world!" # 字符串可以被視爲字符的列表 "This is a string"[0] # => 'T' # % 可以用來格式化字符串 "%s can be %s" % ("strings", "interpolated") # 也可以用 format 方法來格式化字符串 # 推薦使用這個方法 "{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' 可以用來比較對象的相等性 # 這個操作符在比較原始數據時沒多少用,但是比較對象時必不可少 # None, 0, 和空字符串都被算作 False # 其他的均爲 True 0 == False # => True "" == False # => True #################################################### ## 2. 變量和集合 #################################################### # 很方便的輸出 print "I'm Python. Nice to meet you!" # 給變量賦值前不需要事先聲明 some_var = 5 # 一般建議使用小寫字母和下劃線組合來做爲變量名 some_var # => 5 # 訪問未賦值的變量會拋出異常 # 可以查看控制流程一節來了解如何異常處理 some_other_var # 拋出 NameError # if 語句可以作爲表達式來使用 "yahoo!" if 3 > 2 else 2 # => "yahoo!" # 列表用來保存序列 li = [] # 可以直接初始化列表 other_li = [4, 5, 6] # 在列表末尾添加元素 li.append(1) # li 現在是 [1] li.append(2) # li 現在是 [1, 2] li.append(4) # li 現在是 [1, 2, 4] li.append(3) # li 現在是 [1, 2, 4, 3] # 移除列表末尾元素 li.pop() # => 3 li 現在是 [1, 2, 4] # 重新加進去 li.append(3) # li is now [1, 2, 4, 3] again. # 像其他語言訪問數組一樣訪問列表 li[0] # => 1 # 訪問最後一個元素 li[-1] # => 3 # 越界會拋出異常 li[4] # 拋出越界異常 # 切片語法需要用到列表的索引訪問 # 可以看做數學之中左閉右開區間 li[1:3] # => [2, 4] # 省略開頭的元素 li[2:] # => [4, 3] # 省略末尾的元素 li[:3] # => [1, 2, 4] # 刪除特定元素 del li[2] # li 現在是 [1, 2, 3] # 合併列表 li + other_li # => [1, 2, 3, 4, 5, 6] - 並不會不改變這兩個列表 # 通過拼接來合併列表 li.extend(other_li) # li 是 [1, 2, 3, 4, 5, 6] # 用 in 來返回元素是否在列表中 1 in li # => True # 返回列表長度 len(li) # => 6 # 元組類似於列表,但它是不可改變的 tup = (1, 2, 3) tup[0] # => 1 tup[0] = 3 # 類型錯誤 # 對於大多數的列表操作,也適用於元組 len(tup) # => 3 tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) tup[:2] # => (1, 2) 2 in tup # => True # 你可以將元組解包賦給多個變量 a, b, c = (1, 2, 3) # a 是 1,b 是 2,c 是 3 # 如果不加括號,將會被自動視爲元組 d, e, f = 4, 5, 6 # 現在我們可以看看交換兩個數字是多麼容易的事 e, d = d, e # d 是 5,e 是 4 # 字典用來儲存映射關係 empty_dict = {} # 字典初始化 filled_dict = {"one": 1, "two": 2, "three": 3} # 字典也用中括號訪問元素 filled_dict["one"] # => 1 # 把所有的鍵保存在列表中 filled_dict.keys() # => ["three", "two", "one"] # 鍵的順序並不是唯一的,得到的不一定是這個順序 # 把所有的值保存在列表中 filled_dict.values() # => [3, 2, 1] # 和鍵的順序相同 # 判斷一個鍵是否存在 "one" in filled_dict # => True 1 in filled_dict # => False # 查詢一個不存在的鍵會拋出 KeyError filled_dict["four"] # KeyError # 用 get 方法來避免 KeyError filled_dict.get("one") # => 1 filled_dict.get("four") # => None # get 方法支持在不存在的時候返回一個默認值 filled_dict.get("one", 4) # => 1 filled_dict.get("four", 4) # => 4 # setdefault 是一個更安全的添加字典元素的方法 filled_dict.setdefault("five", 5) # filled_dict["five"] 的值爲 5 filled_dict.setdefault("five", 6) # filled_dict["five"] 的值仍然是 5 # 集合儲存無順序的元素 empty_set = set() # 初始化一個集合 some_set = set([1, 2, 2, 3, 4]) # filled_set 現在是 set([1, 2, 3, 4]) # Python 2.7 之後,大括號可以用來表示集合 filled_set = {1, 2, 2, 3, 4} # => {1 2 3 4} # 向集合添加元素 filled_set.add(5) # filled_set 現在是 {1, 2, 3, 4, 5} # 用 & 來計算集合的交 other_set = {3, 4, 5, 6} filled_set & other_set # => {3, 4, 5} # 用 | 來計算集合的並 filled_set | other_set # => {1, 2, 3, 4, 5, 6} # 用 - 來計算集合的差 {1, 2, 3, 4} - {2, 3, 5} # => {1, 4} # 用 in 來判斷元素是否存在於集合中 2 in filled_set # => True 10 in filled_set # => False #################################################### ## 3. 控制流程 #################################################### # 新建一個變量 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: # 這個 elif 語句是不必須的 print "some_var is smaller than 10." else: # 這個 else 也不是必須的 print "some_var is indeed 10." """ 用for循環遍歷列表 輸出: dog is a mammal cat is a mammal mouse is a mammal """ for animal in ["dog", "cat", "mouse"]: # 你可以用 % 來格式化字符串 print "%s is a mammal" % animal """ `range(number)` 返回從0到給定數字的列表 輸出: 0 1 2 3 """ for i in range(4): print i """ while 循環 輸出: 0 1 2 3 """ 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 就是什麼都不做,不過通常這裏會做一些恢復工作 #################################################### ## 4. 函數 #################################################### # 用 def 來新建函數 def add(x, y): print "x is %s and y is %s" % (x, y) return x + y # 通過 return 來返回值 # 調用帶參數的函數 add(5, 6) # => 輸出 "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} """ # 當調用函數的時候,我們也可以進行相反的操作,把元組和字典展開爲參數 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) # 函數在 python 中是一等公民 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 # 內置高階函數 map(add_10, [1, 2, 3]) # => [11, 12, 13] filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] # 可以用列表方法來對高階函數進行更巧妙的引用 [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] #################################################### ## 5. 類 #################################################### # 我們新建的類是從 object 類中繼承的 class Human(object): # 類屬性,由所有類的對象共享 species = "H. sapiens" # 基本構造函數 def __init__(self, name): # 將參數賦給對象成員屬性 self.name = name # 成員方法,參數要有 self def say(self, msg): return "%s: %s" % (self.name, msg) # 類方法由所有類的對象共享 # 這類方法在調用時,會把類本身傳給第一個參數 @classmethod def get_species(cls): return cls.species # 靜態方法是不需要類和對象的引用就可以調用的方法 @staticmethod def grunt(): return "*grunt*" # 實例化一個類 i = Human(name="Ian") print i.say("hi") # 輸出 "Ian: hi" j = Human("Joel") print j.say("hello") # 輸出 "Joel: hello" # 訪問類的方法 i.get_species() # => "H. sapiens" # 改變共享屬性 Human.species = "H. neanderthalensis" i.get_species() # => "H. neanderthalensis" j.get_species() # => "H. neanderthalensis" # 訪問靜態變量 Human.grunt() # => "*grunt*" #################################################### ## 6. 模塊 #################################################### # 我們可以導入其他模塊 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 # Python的模塊其實只是普通的python文件 # 你也可以創建自己的模塊,並且導入它們 # 模塊的名字就和文件的名字相同 # 也可以通過下面的方法查看模塊中有什麼屬性和方法 import math dir(math)
更多閱讀
希望學到更多?試試下面的鏈接:
- Learn Python The Hard Way
- Dive Into Python
- The Official Docs
- Hitchhiker’s Guide to Python
- Python Module of the Week
Translated by: Chenbo Li
http://learnxinyminutes.com/docs/zh-cn/python-cn/