Y分鐘學會Python
Python由Guido Van Rossum發明于90年代初期,是目前最流行的編程語言之一,因其語法的清晰簡潔我愛上了Python,其代碼基本上可以 說是可執行的偽代碼。
非常歡迎反饋!你可以通過推特@louiedinh或louiedinh AT gmail聯系我。
備注:本文是專門針對Python 2.7的,但應該是適用于Python 2.x的。很快我也會為Python 3寫這樣的一篇文章!
# 單行注釋以井字符開頭 """ 我們可以使用三個雙引號(")或單引號(') 來編寫多行注釋 """ ########################################################## ## 1. 基本數據類型和操作符 ########################################################## # 數字 3 #=> 3 # 你預想的數學運算 1 + 1 #=> 2 8 - 1 #=> 7 10 * 2 #=> 20 35 / 5 #=> 7 # 除法略顯詭異。整數相除會自動向下取小于結果的最大整數 11 / 4 #=> 2 # 還有浮點數和浮點數除法(譯注:除數和被除數兩者至少一個為浮點數,結果才會是浮點數) 2.0 # 這是一個浮點數 5.0 / 2.0 #=> 2.5 額...語法更明確一些 # 使用括號來強制優先級 (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' # None是一個對象 None #=> None #################################################### ## 2. 變量與數據容器 #################################################### # 打印輸出非常簡單 print "I'm Python. Nice to meet you!" # 賦值之前不需要聲明變量 some_var = 5 # 約定使用 小寫_字母_和_下劃線 的命名方式 some_var #=> 5 # 訪問之前未賦值的變量會產生一個異常 try: some_other_var except NameError: print "Raises a name error" # 賦值時可以使用條件表達式 some_var = a if a > b else b # 如果a大于b,則將a賦給some_var, # 否則將b賦給some_var # 列表用于存儲數據序列 li = [] # 你可以一個預先填充的列表開始 other_li = [4, 5, 6] # 使用append將數據添加到列表的末尾 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] # 使用pop從列表末尾刪除數據 li.pop() #=> 3,li現在為[1, 2, 4] # 把剛剛刪除的數據存回來 li.append(3) # 現在li再一次為[1, 2, 4, 3] # 像訪問數組一樣訪問列表 li[0] #=> 1 # 看看最后一個元素 li[-1] #=> 3 # 越界訪問會產生一個IndexError try: li[4] # 拋出一個IndexError異常 except IndexError: print "Raises an IndexError" # 可以通過分片(slice)語法來查看列表中某個區間的數據 # 以數學角度來說,這是一個閉合/開放區間 li[1:3] #=> [2, 4] # 省略結束位置 li[2:] #=> [4, 3] # 省略開始位置 li[:3] #=> [1, 2, 4] # 使用del從列表中刪除任意元素 del li[2] #li現在為[1, 2, 3] # 列表可以相加 li + other_li #=> [1, 3, 3, 4, 5, 6] - 注意:li和other_li并未改變 # 以extend來連結列表 li.extend(other_li) # 現在li為[1, 2, 3, 4, 5, 6] # 以in來檢測列表中是否存在某元素 1 in li #=> True # 以len函數來檢測列表長度 len(li) #=> 6 # 元組類似列表,但不可變 tup = (1, 2, 3) tup[0] #=> 1 try: tup[0] = 3 # 拋出一個TypeError異常 except TypeError: print "Tuples cannot be mutated." # 可以在元組上使用和列表一樣的操作 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"] # 注意 - 字典鍵的順序是不確定的 # 你的結果也許和上面的輸出結果并不一致 # 以in來檢測字典中是否存在某個鍵 "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() # 以幾個值初始化一個集合 filled_set = set([1, 2, 2, 3, 4]) # filled_set現為set([1, 2, 3, 4, 5]) # 以&執行集合交運算 other_set = set([3, 4, 5, 6]) filled_set & other_set #=> set([3, 4, 5]) # 以|執行集合并運算 filled_set | other_set #=> set([1, 2, 3, 4, 5, 6]) # 以-執行集合差運算 set([1, 2, 3, 4]) - set([2, 3, 5]) #=> set([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: print "some_var is smaller than 10." 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 """ 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就是什么都不干。通常這里用來做一些恢復工作 # 對于Python 2.7及以下版本有效 try: raise IndexError("This is an index error") except IndexError, e: # 沒有"as",以逗號替代 pass #################################################### ## 4. 函數 #################################################### # 使用def來創建新函數 def add(x, y): print "x is %s and y is %s" % (x, y) return x + y # 以一個return語句來返回值 # 以參數調用函數 add(5, 6) #=> 11 并輸出 "x is 5 and y is 6" # 另一種調用函數的方式是關鍵字參數 add(x=5, y=6) # 關鍵字參數可以任意順序輸入 # 可定義接受可變數量的位置參數的函數 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": "foo", "loch": "ness"} # 也可以一次性接受兩種參數 def all_the_args(*args, **kwargs): print args print kwargs """ all_the_args(1, 2, a=3, b=4)輸出: [1, 2] {"a": 3, "b": 4} """ # 在調用一個函數時也可以使用*和** args = (1, 2, 3, 4) kwargs = {"a": 3, "b": 4} foo(*args) #等價于foo(1, 2, 3, 4) foo(**kwargs) # 等價于foo(a=3, b=4) foo(*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 # 也有匿名函數 (lamda x: x > 2)(3) #=> True # 有一些內置的高階函數 map(add_10, [1, 2, 3]) #=> [11, 12, 13] filter(lamda x: x > 5, [3, 4, 5, 6, 7]) #=>[6, 7] # 可以使用列表推導來實現映射和過濾 [add_10(i) for i in [1, 2, 3]] #=> [11, 13, 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): # 將參數賦值給實例的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*" {% endhighlight %}
進一步閱讀
想要學習更多?試試笨方法學習Python。
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!