国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

以一段代碼為實例快速入門Python2.7

2020-02-23 00:28:53
字體:
來源:轉載
供稿:網友

Python由Guido Van Rossum發明于90年代初期,是目前最流行的編程語言之一,因其語法的清晰簡潔我愛上了Python,其代碼基本上可以 說是可執行的偽代碼。

非常歡迎反饋!你可以通過推特@louiedinh或louiedinh AT gmail聯系我。

備注:本文是專門針對Python 2.7的,但應該是適用于Python 2.x的。很快我也會為Python 3寫這樣的一篇文章!

# 單行注釋以井字符開頭""" 我們可以使用三個雙引號(")或單引號(')  來編寫多行注釋""" ############################################################ 1. 基本數據類型和操作符########################################################## # 數字3 #=> 3 # 你預想的數學運算1 + 1 #=> 28 - 1 #=> 710 * 2 #=> 2035 / 5 #=> 7 # 除法略顯詭異。整數相除會自動向下取小于結果的最大整數11 / 4 #=> 2 # 還有浮點數和浮點數除法(譯注:除數和被除數兩者至少一個為浮點數,結果才會是浮點數)2.0   # 這是一個浮點數5.0 / 2.0 #=> 2.5 額...語法更明確一些 # 使用括號來強制優先級(1 + 3) * 2 #=> 8 # 布爾值也是基本類型數據TrueFalse # 使用not來求反not True #=> Falsenot False #=> True # 相等比較使用==1 == 1 #=> True2 == 1 #=> False # 不相等比較使用!=1 != 1 #=> False2 != 1 #=> True # 更多的比較方式1 < 10 #=> True1 > 10 #=> False2 <= 2 #=> True2 >= 2 #=> True # 比較操作可以串接!1 < 2 < 3 #=> True2 < 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_varexcept 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 # 越界訪問會產生一個IndexErrortry:  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] #=> 1try:  tup[0] = 3 # 拋出一個TypeError異常except TypeError:  print "Tuples cannot be mutated." # 可以在元組上使用和列表一樣的操作len(tup) #=> 3tup + (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 #=> True1 in filled_dict #=> False # 試圖使用某個不存在的鍵會拋出一個KeyError異常filled_dict['four'] #=> 拋出KeyError異常 # 使用get方法來避免KeyErrorfilled_dict.get("one") #=> 1filled_dict.get("four") #=> None # get方法支持一個默認參數,不存在某個鍵時返回該默認參數值filled_dict.get("one", 4) #=> 1filled_dict.get("four", 4) #=> 4 # setdefault方法是一種添加新的鍵-值對到字典的安全方式filled_dict.setdefault("five", 5) #filled_dict["five"]設置為5filled_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 #=> True10 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 = 0while 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 %}            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 鹤壁市| 浦城县| 论坛| 利辛县| 洛隆县| 和静县| 岫岩| 吴桥县| 久治县| 重庆市| 西华县| 汾阳市| 云浮市| 宜丰县| 营山县| 从江县| 兴和县| 英超| 丁青县| 綦江县| 青阳县| 泊头市| 河北区| 麟游县| 稻城县| 双牌县| 乡宁县| 尼勒克县| 丰原市| 蓝山县| 花莲市| 大足县| 延庆县| 政和县| 常宁市| 肇庆市| 潜山县| 西藏| 泰安市| 宁德市| 行唐县|