? ??Python,由吉多·范羅蘇姆(Guido van Rossum)在1989打發圣誕節放假時間的一門“課余”編程項目,至今已有二十多年的歷史,語法簡潔清晰,深受喜愛;
- 小窺
# 查看版本 python -V # 輸出 print "hello" # 輸入 str = raw_input("press any key") print str# 注釋 print "www.cnblogs.com" # link # 幫助 dir(list) help(list)
- 變量
# 無需聲明和刪除,直接賦值;type為內置函數,查詢類型; a = 10 print a,type(a) a = “hello” print a,type(a) a += “ word” print a,type(a)
- 列表、元組和詞典
##### # 1. 列表:list,數據如同STL <list>,下標從0開始,支持添加刪除 province = ['GuangDong', 'ZheJiang', 'HeNan', 'XinJang', 'HeiLongJiang'] print province[2] province.append(‘HuBei’) delete province[1]# 訪問支持:[下限:上限:步長],上限不包括在內 print province[:3] # idx from 0 to 7 print province[3:] # idx from 3 to end print province[0:5:2] # from 0 to 4 with 2 steps print province[3:0:-1] # from 2 to 1 with -1 steps print province[-1] # the last one print province[-3] # the second one from last ##### # 2. 元組:Tuples,如同list,不過不能改變;如12個月英文名之類的常量 days = ('Morning','Afternoon','Night') print days,type(days)# 字符串是一種triple str = “Hello world” print str[2:5]##### # 3. 詞典:Dictionaries, 如同hash, 元素結構為 key:value;如成績 stu_score = {'ZhangSan':34,'LiSi':98, 'WangWu':99}# 新增key:value str_score['LiLei'] = 100# 刪除key delete str_score['ZhangSan']# 檢查 if str_score.has_key(‘HanMeiMei’):print “got HanMeimei ” else print “not find HanMeiMei”# 打印所有key,values? print stu_score.keys(),str_score.values() values = stu_score.values() values.sort() print values,length(values)
- 循環
# Python中語句后無“;”結尾;無“{}”,通過TAB(4個空格) # 1. while a = 0 while (a < 10)a += a+1;print a # 2. if y = True if y == True:print “y is true” elif y == False:print “y is false” else:print “value of y is error.”#3. For tmp = [1,’a’,’sdfa’,242] for value in tmpprint value# 判斷符號 >, >=, <, <=, ==, !=, in
- 函數
# 定義函數show def show(list, info)for entry in list:print entryreturn input(info) + 1 # input輸出數字 # 表傳指針,bulid-in傳值 list = [1,2,3] info = “press num: “ def show (list, info)list[1]=3info = “changed” show(list, info) print list,info
- 類
# 定義類 class Shapedef __int__(self, x, y): # 構造self.x = xself.y = ydef area():print self.x * self.y shape = Shape(100,20) class Square(Shape) # 繼承def __int__(self, x):self.x = self.y = x# 對象詞典 class_dic = {} class_dic[“Shape”] = Shape(100,20) class_dic[“Square”] = Square(100,20) print class_dic[“Shape”].area print class_dic[“Square”].area
- 模塊
# 模塊:只定義集(庫),比如變量、函數和類 # 可以自定義模塊和模塊包 import test_module import dir.module # 相同類型放一個目錄
- 文件操作
Ofile = open(‘file’, ‘r’) Ofile.seek(45,0) # 支持seek、tell, readline, readlins, wirte, close
- 異常處理
try:a = input(“press characters”) except NameError:print “input a num”
?
[Reference]
http://zh.wikipedia.org/zh-cn/Pythonhttp://www.sthurlow.com/python/http://www.cnblogs.com/vamei/archive/2012/05/28/2521650.html