python經(jīng)典實例.doc_第1頁
python經(jīng)典實例.doc_第2頁
python經(jīng)典實例.doc_第3頁
python經(jīng)典實例.doc_第4頁
python經(jīng)典實例.doc_第5頁
免費(fèi)預(yù)覽已結(jié)束,剩余6頁可下載查看

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報或認(rèn)領(lǐng)

文檔簡介

1 輸出你好#打開新窗口,輸入:#!/usr/bin/python#-*-coding:utf8-*-s1=input(Inputyourname:)print(你好,%s%s1)知識點:*input(某字符串)函數(shù):顯示某字符串,并等待用戶輸入.*print()函數(shù):如何打印.*如何應(yīng)用中文 *如何用多行注釋2 輸出字符串和數(shù)字但有趣的是,在javascript里我們會理想當(dāng)然的將字符串和數(shù)字連接,因為是動態(tài)語言嘛.但在Python里有點詭異,如下:#!/usr/bin/pythona=2b=testc=a+b運(yùn)行這行程序會出錯,提示你字符串和數(shù)字不能連接,于是只好用內(nèi)置函數(shù)進(jìn)行轉(zhuǎn)換#!/usr/bin/python#運(yùn)行這行程序會出錯,提示你字符串和數(shù)字不能連接,于是只好用內(nèi)置函數(shù)進(jìn)行轉(zhuǎn)換a=2b=testc=str(a)+bd=1111e=a+int(d)#Howtoprintmultiplyvaluesprint(cis%s,eis%i%(c,e)知識點:*用int和str函數(shù)將字符串和數(shù)字進(jìn)行轉(zhuǎn)換*打印以#開頭,而不是習(xí)慣的/*打印多個參數(shù)的方式3 列表#!/usr/bin/python#-*-coding:utf8-*-#列表類似Javascript的數(shù)組,方便易用#定義元組word=a,b,c,d,e,f,g#如何通過索引訪問元組里的元素a=word2print(ais:+a)b=word1:3print(bis:)print(b)#index1and2elementsofword.c=word:2print(cis:)print(c)#index0and1elementsofword.d=word0:print(dis:)print(d)#Allelementsofword.#元組可以合并e=word:2+word2:print(eis:)print(e)#Allelementsofword.f=word-1print(fis:)print(f)#Thelastelementsofword.g=word-4:-2print(gis:)print(g)#index3and4elementsofword.h=word-2:print(his:)print(h)#Thelasttwoelements.i=word:-2print(iis:)print(i)#Everythingexceptthelasttwocharactersl=len(word)print(Lengthofwordis:+str(l)print(Addsnewelement)word.append(h)print(word)#刪除元素delword0print(word)delword1:3print(word)知識點:*列表長度是動態(tài)的,可任意添加刪除元素.*用索引可以很方便訪問元素,甚至返回一個子列表*更多方法請參考Python的文檔4 字典#!/usr/bin/pythonx=a:aaa,b:bbb,c:12print(xa)print(xb)print(xc)forkeyinx:print(Keyis%sandvalueis%s%(key,xkey)知識點:*將他當(dāng)Java的Map來用即可.5 字符串比起C/C+,Python處理字符串的方式實在太讓人感動了.把字符串當(dāng)列表來用吧.#!/usr/bin/pythonword=abcdefga=word2print(ais:+a)b=word1:3print(bis:+b)#index1and2elementsofword.c=word:2print(cis:+c)#index0and1elementsofword.d=word0:print(dis:+d)#Allelementsofword.e=word:2+word2:print(eis:+e)#Allelementsofword.f=word-1print(fis:+f)#Thelastelementsofword.g=word-4:-2print(gis:+g)#index3and4elementsofword.h=word-2:print(his:+h)#Thelasttwoelements.i=word:-2print(iis:+i)#Everythingexceptthelasttwocharactersl=len(word)print(Lengthofwordis:+str(l)中文和英文的字符串長度是否一樣?#!/usr/bin/python#-*-coding:utf8-*-s=input(輸入你的中文名,按回車?yán)^續(xù));print(你的名字是:+s)l=len(s)print(你中文名字的長度是:+str(l)知識點: 類似Java,在python3里所有字符串都是unicode,所以長度一致.6 條件和循環(huán)語句#!/usr/bin/python#條件和循環(huán)語句x=int(input(Pleaseenteraninteger:)ifx0:x=0print(Negativechangedtozero)elifx=0:print(Zero)else:print(More)#LoopsLista=cat,window,defenestrateforxina:print(x,len(x)#知識點:#*條件和循環(huán)語句#*如何得到控制臺輸入7 函數(shù)#!/usr/bin/python#-*-coding:utf8-*-defsum(a,b):returna+bfunc=sumr=func(5,6)print(r)#提供默認(rèn)值defadd(a,b=2):returna+br=add(1)print(r)r=add(1,5)print(r)一個好用的函數(shù)#!/usr/bin/python#-*-coding:utf8-*-#Therange()functiona=range(1,10)foriina:print(i)a=range(-2,-11,-3)#The3rdparameterstandsforstepforiina:print(i)知識點: Python 不用來控制程序結(jié)構(gòu),他強(qiáng)迫你用縮進(jìn)來寫程序,使代碼清晰. 定義函數(shù)方便簡單 方便好用的range函數(shù)8 異常處理#!/usr/bin/pythons=input(Inputyourage:)ifs=:raiseException(Inputmustnobeempty.)try:i=int(s)exceptExceptionaserr:print(err)finally:#Cleanupactionprint(Goodbye!)9 文件處理對比Java,python的文本處理再次讓人感動#!/usr/bin/pythonspath=D:/download/baa.txtf=open(spath,w)#Opensfileforwriting.Createsthisfiledoesntexist.f.write(Firstline1.n)f.writelines(Firstline2.)f.close()f=open(spath,r)#Opensfileforreadingforlineinf:print(每一行的數(shù)據(jù)是:%s%line)f.close()知識點: open的參數(shù):r表示讀,w寫數(shù)據(jù),在寫之前先清空文件內(nèi)容,a打開并附加內(nèi)容. 打開文件之后記得關(guān)閉10 類和繼承classBase:def_init_(self):self.data=defadd(self,x):self.data.append(x)defaddtwice(self,x):self.add(x)self.add(x)#ChildextendsBaseclassChild(Base):defplus(self,a,b):returna+boChild=Child()oChild.add(str1)print(oChild.data)print(oChild.plus(2,3)知識點:*self:類似Java的this參數(shù)11 包機(jī)制每一個.py文件稱為一個module,module之間可以互相導(dǎo)入.請參看以下例子:# a.pydefadd_func(a,b):returna+b#b.pyfromaimportadd_func#Alsocanbe:importaprint(Importadd_funcfrommodulea)print(Resultof1plus2is:)print(add_func(1,2)#Ifusingimporta,thenhereshouldbea.add_funcmodule可以定義在包里面.Python定義包的方式稍微有點古怪,假設(shè)我們有一個parent文件夾,該文件夾有一個child子文件夾.child中有一個module a.py . 如何讓Python知道這個文件層次結(jié)構(gòu)?很簡單,每個目錄都放一個名為_init_.py 的文件.該文件內(nèi)容可以為空.這個層次結(jié)構(gòu)如下所示:parent-_init_.py-child-_init_.py-a.pyb.py那么Python如何找到我們定義的module?在標(biāo)準(zhǔn)包sys中,path屬性記錄了Python的包路徑.你可以將之打印出來:importsysprint(sys.path)通常我們可以將module的包路徑放到環(huán)境變量PYTHONPATH中,該環(huán)境變量會自動添加到sys.path屬性.另一種方便的方法是編程中直接指定我們的module路徑到sys.path 中:importsysimportossys.path.append(os.getcwd()+parentchild)print(sys.path)fromaimportadd_funcprint(sys.path)print(Importadd_funcfrommodulea)print(Resultof1plus2is:)print(add_func(1,2)知識點: 如何定義模塊和包 如何將模塊路徑添加到系統(tǒng)路徑,以便python找到它們 如何得到當(dāng)前路徑12 內(nèi)建幫助手冊對比C+,Java的突出進(jìn)步是內(nèi)建Javadoc機(jī)制,程序員可以通過閱讀Javadoc了解函數(shù)用法.Python也內(nèi)建了一些方便函數(shù)以便程序員參考. dir函數(shù): 查看某個類/對象的方法. 如果有某個方法想不起來,請敲dir. 在idle里,試試 dir(list) help函數(shù): 詳細(xì)的類/對象介紹. 在idle里, 試試 help(list)1 遍歷文件夾和文件 import osimport os.path# os,os.path里包含大多數(shù)文件訪問的函數(shù),所以要先引入它們. # 請按照你的實際情況修改這個路徑 rootdir = d:/download for parent,dirnames,filenames in os.walk(rootdir): # case1: for dirname in dirnames: print ( parentis: + parent) print ( dirnameis: + dirname) # case2 for filename in filenames: print ( parentis: + parent) print ( filenamewithfullpath: + os.path.join(parent,filename) 知識點:*os.walk返回一個三元組.其中dirnames是所有文件夾名字(不包含路徑),filenames是所有文件的名字(不包含路徑).parent表示父目錄.*case1演示了如何遍歷所有目錄.*case2演示了如何遍歷所有文件.*os.path.join(dirname,filename):將形如/a/b/c和d.java變成/a/b/c/d.java. 2 分割路徑和文件名 import os.path# 常用函數(shù)有三種:分隔路徑,找出文件名.找出盤符(windows系統(tǒng)),找出文件的擴(kuò)展名. # 根據(jù)你機(jī)器的實際情況修改下面參數(shù). spath = D:/download/repository.7z # case1: p,f = os.path.split(spath);print ( diris: + p)print ( fileis: + f)# case2: drv,left = os.path.splitdrive(spath);print ( driveris: + drv)print ( leftis: + left)# case3: f,ext = os.path.splitext(spath);print ( fis: + f)print ( extis: + ext) 知識點:這三個函數(shù)都返回二元組.*case1分隔目錄和文件名*case2分隔盤符和文件名*case3分隔文件和擴(kuò)展名 總結(jié):5個函數(shù) os.walk(spath) os.path.split(spath) os.path.splitdrive(spath) os.path.splitext(spath) os.path.join(path1,path2) 3 復(fù)制文件 import shutilimport osimport os.pathsrc = d:downloadtestmyfile1.txt dst = d:downloadtestmyfile2.txt dst2 = d:/download/test/測試文件夾.txt dir1 = os.path.dirn

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論