以一段代碼為實(shí)例快速入門Python2.7
Python由Guido Van Rossum發(fā)明于90年代初期,是目前最流行的編程語言之一,因其語法的清晰簡潔我愛上了Python,其代碼基本上可以 說是可執(zhí)行的偽代碼。
非常歡迎反饋!你可以通過推特@louiedinh或louiedinh AT gmail聯(lián)系我。
備注:本文是專門針對Python 2.7的,但應(yīng)該是適用于Python 2.x的。很快我也會(huì)為Python 3寫這樣的一篇文章!
# 單行注釋以井字符開頭
""" 我們可以使用三個(gè)雙引號(hào)(")或單引號(hào)(')
來編寫多行注釋
"""
##########################################################
## 1. 基本數(shù)據(jù)類型和操作符
##########################################################
# 數(shù)字
3 #=> 3
# 你預(yù)想的數(shù)學(xué)運(yùn)算
1 + 1 #=> 2
8 - 1 #=> 7
10 * 2 #=> 20
35 / 5 #=> 7
# 除法略顯詭異。整數(shù)相除會(huì)自動(dòng)向下取小于結(jié)果的最大整數(shù)
11 / 4 #=> 2
# 還有浮點(diǎn)數(shù)和浮點(diǎn)數(shù)除法(譯注:除數(shù)和被除數(shù)兩者至少一個(gè)為浮點(diǎn)數(shù),結(jié)果才會(huì)是浮點(diǎn)數(shù))
2.0 # 這是一個(gè)浮點(diǎn)數(shù)
5.0 / 2.0 #=> 2.5 額...語法更明確一些
# 使用括號(hào)來強(qiáng)制優(yōu)先級
(1 + 3) * 2 #=> 8
# 布爾值也是基本類型數(shù)據(jù)
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
# 可以使用"或'創(chuàng)建字符串
"This is a string."
'This is also a string.'
# 字符串也可以相加!
"Hello " + "world!" #=> "Hello world!"
# 字符串可以看作是一個(gè)字符列表
"This is a string"[0] #=> 'T'
# None是一個(gè)對象
None #=> None
####################################################
## 2. 變量與數(shù)據(jù)容器
####################################################
# 打印輸出非常簡單
print "I'm Python. Nice to meet you!"
# 賦值之前不需要聲明變量
some_var = 5 # 約定使用 小寫_字母_和_下劃線 的命名方式
some_var #=> 5
# 訪問之前未賦值的變量會(huì)產(chǎn)生一個(gè)異常
try:
some_other_var
except NameError:
print "Raises a name error"
# 賦值時(shí)可以使用條件表達(dá)式
some_var = a if a > b else b
# 如果a大于b,則將a賦給some_var,
# 否則將b賦給some_var
# 列表用于存儲(chǔ)數(shù)據(jù)序列
li = []
# 你可以一個(gè)預(yù)先填充的列表開始
other_li = [4, 5, 6]
# 使用append將數(shù)據(jù)添加到列表的末尾
li.append(1) #li現(xiàn)在為[1]
li.append(2) #li現(xiàn)在為[1, 2]
li.append(4) #li現(xiàn)在為[1, 2, 4]
li.append(3) #li現(xiàn)在為[1, 2, 4, 3]
# 使用pop從列表末尾刪除數(shù)據(jù)
li.pop() #=> 3,li現(xiàn)在為[1, 2, 4]
# 把剛剛刪除的數(shù)據(jù)存回來
li.append(3) # 現(xiàn)在li再一次為[1, 2, 4, 3]
# 像訪問數(shù)組一樣訪問列表
li[0] #=> 1
# 看看最后一個(gè)元素
li[-1] #=> 3
# 越界訪問會(huì)產(chǎn)生一個(gè)IndexError
try:
li[4] # 拋出一個(gè)IndexError異常
except IndexError:
print "Raises an IndexError"
# 可以通過分片(slice)語法來查看列表中某個(gè)區(qū)間的數(shù)據(jù)
# 以數(shù)學(xué)角度來說,這是一個(gè)閉合/開放區(qū)間
li[1:3] #=> [2, 4]
# 省略結(jié)束位置
li[2:] #=> [4, 3]
# 省略開始位置
li[:3] #=> [1, 2, 4]
# 使用del從列表中刪除任意元素
del li[2] #li現(xiàn)在為[1, 2, 3]
# 列表可以相加
li + other_li #=> [1, 3, 3, 4, 5, 6] - 注意:li和other_li并未改變
# 以extend來連結(jié)列表
li.extend(other_li) # 現(xiàn)在li為[1, 2, 3, 4, 5, 6]
# 以in來檢測列表中是否存在某元素
1 in li #=> True
# 以len函數(shù)來檢測列表長度
len(li) #=> 6
# 元組類似列表,但不可變
tup = (1, 2, 3)
tup[0] #=> 1
try:
tup[0] = 3 # 拋出一個(gè)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) # 現(xiàn)在a等于1,b等于2,c等于3
# 如果你省略括號(hào),默認(rèn)也會(huì)創(chuàng)建元組
d, e, f = 4, 5, 6
# 看看兩個(gè)變量互換值有多簡單
e, d = d, e #現(xiàn)在d為5,e為4
# 字典存儲(chǔ)映射關(guān)系
empty_dict = {}
# 這是一個(gè)預(yù)先填充的字典
filled_dict = {"one": 1, "two": 2, "three": 3}
# 以[]語法查找值
filled_dict['one'] #=> 1
# 以列表形式獲取所有的鍵
filled_dict.keys() #=> ["three", "two", "one"]
# 注意 - 字典鍵的順序是不確定的
# 你的結(jié)果也許和上面的輸出結(jié)果并不一致
# 以in來檢測字典中是否存在某個(gè)鍵
"one" in filled_dict #=> True
1 in filled_dict #=> False
# 試圖使用某個(gè)不存在的鍵會(huì)拋出一個(gè)KeyError異常
filled_dict['four'] #=> 拋出KeyError異常
# 使用get方法來避免KeyError
filled_dict.get("one") #=> 1
filled_dict.get("four") #=> None
# get方法支持一個(gè)默認(rèn)參數(shù),不存在某個(gè)鍵時(shí)返回該默認(rèn)參數(shù)值
filled_dict.get("one", 4) #=> 1
filled_dict.get("four", 4) #=> 4
# setdefault方法是一種添加新的鍵-值對到字典的安全方式
filled_dict.setdefault("five", 5) #filled_dict["five"]設(shè)置為5
filled_dict.setdefault("five", 6) #filled_dict["five"]仍為5
# 集合
empty_set = set()
# 以幾個(gè)值初始化一個(gè)集合
filled_set = set([1, 2, 2, 3, 4]) # filled_set現(xiàn)為set([1, 2, 3, 4, 5])
# 以&執(zhí)行集合交運(yùn)算
other_set = set([3, 4, 5, 6])
filled_set & other_set #=> set([3, 4, 5])
# 以|執(zhí)行集合并運(yùn)算
filled_set | other_set #=> set([1, 2, 3, 4, 5, 6])
# 以-執(zhí)行集合差運(yùn)算
set([1, 2, 3, 4]) - set([2, 3, 5]) #=> set([1, 4])
# 以in來檢測集合中是否存在某個(gè)值
2 in filled_set #=> True
10 in filled_set #=> False
####################################################
## 3. 控制流程
####################################################
# 創(chuàng)建個(gè)變量
some_var = 5
# 以下是一個(gè)if語句??s進(jìn)在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循環(huán)在列表上迭代
輸出:
dog is a mammal
cat is a mammal
mouse is a mammal
"""
for animal in ["dog", "cat", "mouse"]:
# 可以使用%來插補(bǔ)格式化字符串
print "%s is a mammal" % animal
"""
while循環(huán)直到未滿足某個(gè)條件。
輸出:
0
1
2
3
"""
x = 0
while x < 4:
print x
x += 1 # x = x + 1的一種簡寫
# 使用try/except塊來處理異常
# 對Python 2.6及以上版本有效
try:
# 使用raise來拋出一個(gè)錯(cuò)誤
raise IndexError("This is an index error")
except IndexError as e:
pass # pass就是什么都不干。通常這里用來做一些恢復(fù)工作
# 對于Python 2.7及以下版本有效
try:
raise IndexError("This is an index error")
except IndexError, e: # 沒有"as",以逗號(hào)替代
pass
####################################################
## 4. 函數(shù)
####################################################
# 使用def來創(chuàng)建新函數(shù)
def add(x, y):
print "x is %s and y is %s" % (x, y)
return x + y # 以一個(gè)return語句來返回值
# 以參數(shù)調(diào)用函數(shù)
add(5, 6) #=> 11 并輸出 "x is 5 and y is 6"
# 另一種調(diào)用函數(shù)的方式是關(guān)鍵字參數(shù)
add(x=5, y=6) # 關(guān)鍵字參數(shù)可以任意順序輸入
# 可定義接受可變數(shù)量的位置參數(shù)的函數(shù)
def varargs(*args):
return args
varargs(1, 2, 3) #=> (1, 2, 3)
# 也可以定義接受可變數(shù)量關(guān)鍵字參數(shù)的函數(shù)
def keyword_args(**kwargs):
return kwargs
# 調(diào)用一下該函數(shù)看看會(huì)發(fā)生什么
keyword_args(big="foot", loch="ness") #=> {"big": "foo", "loch": "ness"}
# 也可以一次性接受兩種參數(shù)
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}
"""
# 在調(diào)用一個(gè)函數(shù)時(shí)也可以使用*和**
args = (1, 2, 3, 4)
kwargs = {"a": 3, "b": 4}
foo(*args) #等價(jià)于foo(1, 2, 3, 4)
foo(**kwargs) # 等價(jià)于foo(a=3, b=4)
foo(*args, **kwargs) # 等價(jià)于foo(1, 2, 3, 4, a=3, b=4)
# Python的函數(shù)是一等函數(shù)
def create_adder(x):
def adder(y):
return x + y
return adder
add_10 = create_adder(10)
add_10(3) #=> 13
# 也有匿名函數(shù)
(lamda x: x > 2)(3) #=> True
# 有一些內(nèi)置的高階函數(shù)
map(add_10, [1, 2, 3]) #=> [11, 12, 13]
filter(lamda x: x > 5, [3, 4, 5, 6, 7]) #=>[6, 7]
# 可以使用列表推導(dǎo)來實(shí)現(xiàn)映射和過濾
[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. 類
####################################################
# 創(chuàng)建一個(gè)子類繼承自object來得到一個(gè)類
class Human(object):
# 類屬性。在該類的所有示例之間共享
species = "H. sapiens"
# 基本初始化構(gòu)造方法
def __init__(self, name):
# 將參數(shù)賦值給實(shí)例的name屬性
self.name = name
# 實(shí)例方法。所有示例方法都以self為第一個(gè)參數(shù)
def say(self, msg):
return "%s: %s" % (self.name, msg)
# 類方法由所有實(shí)例共享
# 以調(diào)用類為第一個(gè)參數(shù)進(jìn)行調(diào)用
@classmethod
def get_species(cls):
return cls.species
# 靜態(tài)方法的調(diào)用不需要一個(gè)類或?qū)嵗囊?
@staticmethod
def grunt():
return "*grunt*"
# 實(shí)例化一個(gè)類
i = Human(name="Ian")
print i.say("hi") # 輸出"Ian: hi"
j = Human("Joel")
print j.say("hello") # 輸出"Joel: hello"
# 調(diào)用類方法
i.get_species() #=> "H. sapiens"
# 修改共享屬性
Human.species = "H. neanderthalensis"
i.get_species() #=> "H. neanderthalensis"
j.get_species() #=> "H. neanderthalensis"
# 調(diào)用靜態(tài)方法
Human.grunt() #=> "*grunt*"
{% endhighlight %}
相關(guān)文章
使用python怎樣產(chǎn)生10個(gè)不同的隨機(jī)數(shù)
這篇文章主要介紹了使用python實(shí)現(xiàn)產(chǎn)生10個(gè)不同的隨機(jī)數(shù)方式,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-07-07
Django QuerySet查詢集原理及代碼實(shí)例
這篇文章主要介紹了Django QuerySet查詢集原理及代碼實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-06-06
基于Python批量鑲嵌拼接遙感影像/柵格數(shù)據(jù)(示例代碼)
這篇文章主要介紹了基于Python批量鑲嵌拼接遙感影像/柵格數(shù)據(jù),使用時(shí)直接修改Mosaic_GDAL函數(shù)的入?yún)⒕托辛?選擇數(shù)據(jù)存放的路徑會(huì)自動(dòng)拼接,命名也會(huì)自己設(shè)置無需額外修改,需要的朋友可以參考下2023-10-10
十行Python3代碼實(shí)現(xiàn)把情書寫到圖片中
這篇文章主要為大家介紹了如何利用Python語言實(shí)現(xiàn)將情書寫到照片中,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起了解一下2022-04-04
跟老齊學(xué)Python之大話題小函數(shù)(2)
上篇文章我們講訴了map 和lambda函數(shù)的使用,本文我們繼續(xù)來看看reduce和filter函數(shù),有需要的朋友可以參考下2014-10-10
Python的Twisted框架中使用Deferred對象來管理回調(diào)函數(shù)
當(dāng)說起Twisted的異步與非阻塞模式等特性時(shí),回調(diào)函數(shù)的使用在其中自然就顯得不可或缺,接下來我們就來看Python的Twisted框架中使用Deferred對象來管理回調(diào)函數(shù)的用法.2016-05-05

