Python入門經典實例參考模板_第1頁
Python入門經典實例參考模板_第2頁
Python入門經典實例參考模板_第3頁
Python入門經典實例參考模板_第4頁
Python入門經典實例參考模板_第5頁
已閱讀5頁,還剩10頁未讀 繼續免費閱讀

下載本文檔

版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領

文檔簡介

1、1 你好#打開新窗口,輸入:#! /usr/bin/python# -*- coding: utf8 -*- s1=input("Input your name:")print("你好,%s" % s1)'''知識點:    * input("某字符串")函數:顯示"某字符串",并等待用戶輸入.    *

2、 print()函數:如何打印.    * 如何應用中文    * 如何用多行注釋'''    2 字符串和數字但有趣的是,在javascript里我們會理想當然的將字符串和數字連接,因為是動態語言嘛.但在Python里有點詭異,如下:#! /usr/bin/pythona=2b="test"c=a+b運行這行程序會出錯,提示你字符串和數字不能連接,于是只好用內置函數進行轉換#! /usr/b

3、in/python#運行這行程序會出錯,提示你字符串和數字不能連接,于是只好用內置函數進行轉換a=2b="test"c=str(a)+bd="1111"e=a+int(d)#How to print multiply valuesprint ("c is %s,e is %i" % (c,e)'''知識點:    * 用int和str函數將字符串和數字進

4、行轉換    * 打印以#開頭,而不是習慣的/    * 打印多個參數的方式    '''1 / 153 列表#! /usr/bin/python# -*- coding: utf8 -*-#列表類似Javascript的數組,方便易用#定義元組word='a','b','c','d','e','

5、f','g'#如何通過索引訪問元組里的元素a=word2print ("a is: "+a)b=word1:3print ("b is: ")print (b) # index 1 and 2 elements of word.c=word:2print ("c is: ")print (c) # ind

6、ex 0 and 1 elements of word.d=word0:print ("d is: ")print (d) # All elements of word.#元組可以合并e=word:2+word2:print ("e is: ")print (e) # All elements of word.f=wo

7、rd-1print ("f is: ")print (f) # The last elements of word.g=word-4:-2print ("g is: ")print (g) # index 3 and 4 elements of word.h=word-2:print ("h is: 

8、;")print (h) # The last two elements.i=word:-2print ("i is: ")print (i) # Everything except the last two charactersl=len(word)print ("Length of word is: "+ str(

9、l)print ("Adds new element")word.append('h')print (word)#刪除元素del word0print (word)del word1:3print (word)'''知識點:    * 列表長度是動態的,可任意添加刪除元素.    * 用索引可以很方便訪問元素,甚至返回一個子列表  

10、60; * 更多方法請參考Python的文檔'''4 字典#! /usr/bin/pythonx='a':'aaa','b':'bbb','c':12print (x'a')print (x'b')print (x'c')for key in x:    print ("Key is&#

11、160;%s and value is %s" % (key,xkey)    '''知識點:    * 將他當Java的Map來用即可.'''5 字符串比起C/C+,Python處理字符串的方式實在太讓人感動了.把字符串當列表來用吧.#! /usr/bin/pythonword="abcdefg"a=word2print ("a 

12、;is: "+a)b=word1:3print ("b is: "+b) # index 1 and 2 elements of word.c=word:2print ("c is: "+c) # index 0 and 1 elements of word.d=word0:print ("d

13、60;is: "+d) # All elements of word.e=word:2+word2:print ("e is: "+e) # All elements of word.f=word-1print ("f is: "+f) # The last elements of word.g=word-4:-2pr

14、int ("g is: "+g) # index 3 and 4 elements of word.h=word-2:print ("h is: "+h) # The last two elements.i=word:-2print ("i is: "+i) # Everything ex

15、cept the last two charactersl=len(word)print ("Length of word is: "+ str(l)中文和英文的字符串長度是否一樣?#! /usr/bin/python# -*- coding: utf8 -*- s=input("輸入你的中文名,按回車繼續");print ("你的名字是  : &

16、quot; +s)l=len(s)print ("你中文名字的長度是:"+str(l)知識點:· 類似Java,在python3里所有字符串都是unicode,所以長度一致.6 條件和循環語句#! /usr/bin/python#條件和循環語句x=int(input("Please enter an integer:")if x<0:    x=0    print ("

17、Negative changed to zero")elif x=0:    print ("Zero")else:    print ("More")# Loops Lista = 'cat', 'window', 'defenestrate'for x in a:&#

18、160;   print (x, len(x)#知識點:#    * 條件和循環語句#    * 如何得到控制臺輸入7 函數#! /usr/bin/python# -*- coding: utf8 -*- def sum(a,b):    return a+bfunc = sumr = f

19、unc(5,6)print (r)# 提供默認值def add(a,b=2):    return a+br=add(1)print (r)r=add(1,5)print (r)一個好用的函數#! /usr/bin/python# -*- coding: utf8 -*- # The range() functiona =range (1,10)for i in

20、60;a:    print (i)    a = range(-2,-11,-3) # The 3rd parameter stands for stepfor i in a:    print (i)知識點:· Python 不用來控制程序結構,他強迫你用縮進來寫程序,使代碼清晰. · 定義函數方便簡單 ·

21、; 方便好用的range函數8 異常處理#! /usr/bin/pythons=input("Input your age:")if s ="":    raise Exception("Input must no be empty.")try:    i=int(s)except Exception as err: 

22、   print(err)finally: # Clean up action    print("Goodbye!")9 文件處理對比Java,python的文本處理再次讓人感動#! /usr/bin/pythonspath="D:/download/baa.txt"f=open(spath,"w") # Opens file for writing.Creates

23、 this file doesn't exist.f.write("First line 1.n")f.writelines("First line 2.")f.close()f=open(spath,"r") # Opens file for readingfor line in f:    print("每一行的數據

24、是:%s"%line)f.close()知識點:· open的參數:r表示讀,w寫數據,在寫之前先清空文件內容,a打開并附加內容. · 打開文件之后記得關閉10 類和繼承class Base:    def _init_(self):        self.data =     def add(self, x):   

25、;     self.data.append(x)    def addtwice(self, x):        self.add(x)        self.add(x)# Child extends Baseclass Child(Base):   

26、 def plus(self,a,b):        return a+boChild =Child()oChild.add("str1")print (oChild.data)print (oChild.plus(2,3)'''知識點:    * self:類似Java的this參數    '''

27、11 包機制每一個.py文件稱為一個module,module之間可以互相導入.請參看以下例子:# a.pydef add_func(a,b):    return a+b# b.pyfrom a import add_func # Also can be : import aprint ("Import add_func from module a")pr

28、int ("Result of 1 plus 2 is: ")print (add_func(1,2)    # If using "import a" , then here should be "a.add_func"module可以定義在包里面.Python定義包的方式稍微有點古怪,假設我們有一個parent文件

29、夾,該文件夾有一個child子文件夾.child中有一個module a.py . 如何讓Python知道這個文件層次結構?很簡單,每個目錄都放一個名為_init_.py 的文件.該文件內容可以為空.這個層次結構如下所示:parent   -_init_.py  -child    - _init_.py    -a.pyb.py那么Python如何找到我們定義的module?在標準包sys中,path屬性記錄了Python的包路徑.你可以將之打印出來:i

30、mport sysprint(sys.path)通常我們可以將module的包路徑放到環境變量PYTHONPATH中,該環境變量會自動添加到sys.path屬性.另一種方便的方法是編程中直接指定我們的module路徑到sys.path 中:import sysimport ossys.path.append(os.getcwd()+'parentchild')print(sys.path)from a import add_funcprint (sys.path)print ("Impor

31、t add_func from module a")print ("Result of 1 plus 2 is: ")print (add_func(1,2)知識點:· 如何定義模塊和包 · 如何將模塊路徑添加到系統路徑,以便python找到它們 · 如何得到當前路徑12 內建幫助手冊對比C+,Java的突出進步是內建Javadoc機制,程序員可以通過閱讀Javadoc了解函數用法.Python也內建了一些方便函數以

32、便程序員參考.· dir函數: 查看某個類/對象的方法. 如果有某個方法想不起來,請敲dir. 在idle里,試試 dir(list) · help函數: 詳細的類/對象介紹. 在idle里, 試試 help(list)1 遍歷文件夾和文件 import  osimport  os.path#  os,os.path里包含大多數文件訪問的函數,所以要先引入它們. #  請按照你的實際情況修改這個路徑 rootdir  =   " d:/download " for  parent,&#

33、160;dirnames, filenames  in  os.walk(rootdir):     # case 1:      for  dirname  in  dirnames:         print  ( " parent is: "   +  parent)   

34、;      print  ( " dirname is: "   +  dirname)     # case 2      for  filename  in  filenames:         print  ( " parent is: "

35、   +  parent)         print  ( " filename with full path : "   +  os.path.join(parent, filename)''' 知識點:    * os.walk返回一個三元組.其中dirnames是所有文件夾名字(不包含路徑),filenames是所有

36、文件的名字(不包含路徑).parent表示父目錄.    * case1 演示了如何遍歷所有目錄.    * case2 演示了如何遍歷所有文件.    * os.path.join(dirname,filename) : 將形如"/a/b/c"和"d.java"變成/a/b/c/d.java".''' 2 分割路徑和文件名 impo

37、rt  os.path# 常用函數有三種:分隔路徑,找出文件名.找出盤符(windows系統),找出文件的擴展名. # 根據你機器的實際情況修改下面參數. spath = " D:/download/repository.7z " #  case 1: p,f = os.path.split(spath);print ( " dir is: " + p)print ( " file is: " + f)#  case 2: drv,left = os.path.sp

38、litdrive(spath);print ( " driver is: " + drv)print ( " left is: " + left)#  case 3: f,ext = os.path.splitext(spath);print ( " f is: " + f)print ( " ext is: " + ext)'''     知識點:   

39、0;這三個函數都返回二元組.    * case1 分隔目錄和文件名    * case2 分隔盤符和文件名    * case3 分隔文件和擴展名''' 總結:5個函數 · os.walk(spath) · os.path.split(spath) · os.path.splitdrive(spath) · os.path.splitext(spath

40、) · os.path.join(path1,path2) 3 復制文件 import  shutilimport  osimport  os.pathsrc = " d:downloadtestmyfile1.txt " dst = " d:downloadtestmyfile2.txt " dst2 = " d:/download/test/測試文件夾.txt " dir1 = os.path.dirname(src)print ( " dir1 %s " %

41、dir1)if (os.path.exists(src) = False):    os.makedirs(dir1)       f1 = open(src, " w " )f1.write( " line an " )f1.write( " line bn " )f1.close()shutil.copyfile(src, dst)shutil.copyfile(src, dst2)

42、f2 = open(dst, " r " )for  line  in  f2:     print (line)f2.close()# 測試復制文件夾樹 try :    srcDir = " d:/download/test "     dstDir = " d:/download/test2 "      # 如果dstDir已經存在,那么s

43、hutil.copytree方法會報錯!      # 這也意味著你不能直接用d:作為目標路徑.     shutil.copytree(srcDir, dstDir)except  Exception as err:     print  (err)    '''     知識點:   

44、60;* shutil.copyfile:如何復制文件    * os.path.exists:如何判斷文件夾是否存在    * shutil.copytree:如何復制目錄樹    ''' 總結:4個函數 · os.path.dirname(path) · os.path.exists(path) · shutil.copyfile(src, dst) · shutil.copyt

45、ree(srcDir, dstDir) 4 實戰:文件備份小程序 import  osimport  shutilimport  datetime''' 作用:將目錄備份到其他路徑。實際效果:假設給定目錄"/media/data/programmer/project/python" ,備份路徑"/home/diegoyun/backup/“ ,則會將python目錄備份到備份路徑下,形如:/home/diegoyun/backup/yyyymmddHHMMSS/python/xxx/yyy/

46、zzz.用法:更改這兩個參數.backdir:備份目的地.copydirs:想要備份的文件夾.''' def  mainLogic():     # add dirs you want to copy     backdir = " d:test "      print (backdir)    copydirs =  &

47、#160;  copydirs.append( " d:temp " );     # copydirs.append("d:test");              print ( " Copying files  = " )    start = datetime.datetime.n

48、ow()     # gen a data folder for backup     backdir = os.path.join(backdir,start.strftime( " %Y-%m-%d " )     # print("backdir is:"+backdir)         k

49、c = 0     for  d  in  copydirs:        kc = kc + copyFiles(d,backdir)    end = datetime.datetime.now()     print ( " Finished! = " )     print ( "

50、; Total files :  "   +  str(kc) )     print ( " Elapsed time :  "   +  str(end - start).seconds) + "  seconds " )def  copyFiles(copydir,backdir):    prefix = getPathPrefi

51、x(copydir)     # print("prefix is:"+prefix )        i = 0     for  dirpath,dirnames,filenames  in  os.walk(copydir):         for  name  in &

52、#160;filenames:            oldpath = os.path.join(dirpath,name)            newpath = omitPrefix(dirpath,prefix)           

53、60; print ( " backdir is: " + backdir )                       newpath = os.path.join(backdir,newpath)             print ( " newpath is: "

溫馨提示

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

評論

0/150

提交評論