


下載本文檔
版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認(rèn)領(lǐng)
文檔簡介
1、實例教程:1小時學(xué)會Python1序言面向讀者本文適合有經(jīng)驗的程序員盡快進入Python2.x 世界.特別地,如果你掌握J(rèn)ava和Javascript,不用1小時你就可以用Python快速流暢地寫有用的 Python程序.Python3.x 用戶請參考:由于Django 不支持python3,所以為了你的開展?jié)摿?,建議你學(xué)習(xí)python2.x 為什么使用Pytho n假設(shè)我們有這么一項任務(wù):簡單測試局域網(wǎng)中的電腦是否連通 .這些電腦的ipX圍從到192.168.0.200.思路:用shell編程.Linux 通常是bash而Windows 是批處理腳本.例如,在Windows 上用ping i
2、p的命令依次測試各個機器并得到控制臺輸出.由于ping通的時候控制臺文本通常是"Reply from ."而不通的時候文本是"time out .", 所以,在結(jié)果中進行字符串查找,即可知道該機器是否連通. 實現(xiàn):Java代碼如下:Str ing cmd="cmd.exe ping "String ipprefix="192.168.10."int begin=101;int end=200;Process p= null ;for (int i=begin;i<end;i+)p= Run time.getR
3、u ntime().exec(cmd+i);String line =null ;BufferedReaderreader=newBufferedReader( newIn putStreamReader(p.getl nputStream();while (line = reader .readLine() != null )/Ha ndli ng line , may logs it.reader .close();p.destroy();這段代碼運行得很好,問題是為了運行這段代碼,你還需要做一些額外的工作.這些額外的工作包括?編寫一個類文件?編寫一個main方法? 將之編譯成字節(jié)代碼?由
4、于字節(jié)代碼不能直接運行,你需要再寫個小小的bat或者bash腳本來運行.當(dāng)然,用C/C+同樣能完成這項工作.但C/C+不是跨平臺語言.在這個足夠簡單的例子中也許看不 岀C/C+和Java實現(xiàn)的區(qū)別,但在一些更為復(fù)雜的場景,比方要將連通與否的信息記錄到網(wǎng)絡(luò)數(shù)據(jù)庫.由于Linux和Windows的網(wǎng)絡(luò)接口實現(xiàn)方式不同,你不得不寫兩個函數(shù)的版本.用Java就沒有這樣的顧慮. 同樣的工作用Python實現(xiàn)如下:比照J(rèn)ava,Python 的實現(xiàn)更為簡潔,你編寫的時間更快.你不需要寫main函數(shù),并且這個程序保存之后 可以直接運行.另外,和Java 樣,Python 也是跨平臺的.有經(jīng)驗的C/Java
5、程序員可能會爭論說用C/Java寫會比Python寫得快.這個觀點見仁見智.我的想法是當(dāng)你同時掌握J(rèn)ava和Python之后,你會發(fā)現(xiàn)用Python寫這類程序的速度會比 Java快上許多.例如操作本地文件時你僅需要一行代碼而不需要Java的許多流包裝類.各種語言有其天然的適合的應(yīng)用X圍.用Python處理一些簡短程序類似與操作系統(tǒng)的交互編程工作最省時省力.Pytho n應(yīng)用場合足夠簡單的任務(wù),例如一些shell編程.如果你喜歡用Python設(shè)計大型商業(yè)或者設(shè)計復(fù)雜的游戲,悉聽尊便.2快速入門2.1 Hello world安裝完P(guān)ython之后(我本機的版本是2.5.4),翻開IDLE(Pyth
6、on GUI),該程序是Python語言解釋器,你寫的語句能夠立即運行.我們寫下一句著名的程序語句:pri nt "Hello,world!"并按回車.你就能看到這句被K&R引入到程序世界的名言.在解釋器中選擇"File"-"NewWindow" 或快捷鍵Ctrl+N ,翻開一個新的編輯器.寫下如下語句:pri nt "Hello,world!"raw_input("Press enter key to close this windowL ");保存為a.py文件.按F5,你就可以看到
7、程序的運行結(jié)果了.這是Python的第二種運行方式. 找到你保存的a.py文件,雙擊.也可以看到程序結(jié)果.Python的程序能夠直接運行,比照J(rèn)ava,這是一個優(yōu)勢.2.2國際化支持我們換一種方式來問候世界.新建一個編輯器并寫如下代碼print "歡送來到奧運中國!"raw_input("Press enter key to close this window-");在你保存代碼的時候,Python會提示你是否改變文件的字符集,結(jié)果如下:# -*- codi ng: cp936 -*- print "歡送來到奧運中國!"raw_in
8、put("Press en ter key to close this wi ndow);將該字符集改為我們更熟悉的形式:# -*- cod ing: GBK -*-print "歡送來到奧運中國!" #使用中文的例子raw_input("Press enter key to close this window");程序一樣運行良好.2.3方便易用的計算器用微軟附帶的計算器來計數(shù)實在太麻煩了.翻開Python解釋器,直接進行計算a=100.02.4 字符串,ASCII 和 UNICODE可以如下打印岀預(yù)定義輸岀格式的字符串print "
9、;"“Usage: thingy OPTIONS-hDisplay this usage message-H host nameHost name to conn ect tomill字符串是怎么訪問的?請看這個例子word="abcdefg"a=word2pri nt "a is: "+ab=word1:3pri nt "b is: "+b # in dex 1 and 2 eleme nts of word.c=word:2pri nt "c is: "+c # in dex 0 and 1 elem
10、e nts of word.d=word0:pri nt "d is: "+d # All eleme nts of word.e=word:2+word2:print "e is: "+e # All elements of word.f=word-1pri nt "f is: "+f # The last eleme nts of word.g=word-4:-2pri nt "g is: "+g # in dex 3 and 4 eleme nts of word.h=word-2:pr int "
11、h is: "+h # The last two eleme nts.i=word:-2print "i is: "+i # Everything except the last two charactersl=le n( word)pri nt "Le ngth of word is: "+ str(l)請注意ASCII和UNICODE字符串的區(qū)別pri nt "In put your Chin ese n ame:"s=raw_ in put("Press en ter to be contin ued);pr
12、int "Your name is :"+s;l=le n(s)print "Le ngth of your Chin ese n ame in asc codes is:"+str(l);a=u nicode(s,"GBK")l=le n(a)pri nt "I'm sorry we should use uni code char!Characters n umber of your Chin ese n ame in uni code is:"+str(l);2.5 使用 List類似Java里的Li
13、st,這是一種方便易用的數(shù)據(jù)類型word='a','b','c','d','e','f','g'a=word2pri nt "a is: "+ab=word1:3pri nt "b is:"pr int b # in dex 1 and 2 eleme nts of word.c=word:2pri nt "c is:"pr int c # in dex 0 and 1 eleme nts of word.d=word0:p
14、ri nt "d is:"pri nt d # All eleme nts of word.e=word:2+word2:pri nt "e is:"pri nt e # All eleme nts of word.f=word-1pri nt "f is:"pri nt f # The last eleme nts of word.g=word-4:-2pri nt "g is:"pr int g # in dex 3 and 4 eleme nts of word.h=word-2:pri nt "h
15、 is:"pri nt h # The last two eleme nts.i=word:-2pri nt "i is:"print i # Everything except the last two charactersl=le n( word)pri nt "Le ngth of word is: "+ str(l)pri nt "Adds new eleme nt2.6條件和循環(huán)語句# Multi-way decisi on x= int (raw input("Please enter an integer:&q
16、uot;) if x<0:x=0pri nt "Negative cha nged to zero" elif x=0:pri nt "Zero" else :pri nt "More"# Loops Lista = 'cat', 'w in dow', 'defe nestrate'for x in a:pr int x, le n(x)2.7如何定義函數(shù)# Define and in voke fun cti on.def sum(a,b):return a+b func =
17、sum r = fun c(5,6) pri nt r# Defines fun cti on with default argume nt def add(a,b=2):return a+br=add(1)pri nt rr=add(1,5)pri nt r并且,介紹一個方便好用的函數(shù):# The ran ge() fun cti ona =ran ge(5,10)pri nt aa = ran ge(-2,-7)pri nt aa = ran ge(_7,_2)pri nt aa = range(-2,-11,-3) # The 3rd parameter standsfor steppr
18、i nt a2.8 文件I/Ospath="D:/dow nload/baa.txt"f=ope n( spath,"w") # Opens filefor writi ng.Createsthis file does n't exist.f.write("First line 1.n")f.writelines("First line 2.") f.close()f=ope n( spath,"r") # Opens filefor read ing for line in f:pri
19、 nt line f.close()2.9異常處理s=raw_ in put("I nput your age:")if s ="":raise Excepti on( T nput must no be empty.") try :i= int (s)except ValueError:pri nt "Could not con vert data to an in teger."except:pri nt "Unknown excepti on!"else : # It is useful for c
20、ode that must be executedif the try clause does not raise anexcepti onpri nt "You are %d" % i," years old"fin ally : # Clea n up acti onpri nt "Goodbye!"2.10類和繼承2.11 包機制每一個.py文件稱為一個module,module之間可以互相導(dǎo)入.請參看以下例子# b.pyfrom a import add_func # Also can be : import a print
21、"Import add func from module a"print "Result of 1 plus 2 is:"print add_func(1,2)# If using "import a" , then here should be "a.add_func"module可以定義在包里面.Python定義包的方式稍微有點乖僻,假設(shè)我們有一個parent文件夾,該文 件夾有一個child子文件夾.child中有一個module a.py . 如何讓Python知道這個文件層次結(jié)構(gòu) ?很簡 單,每個目錄都放一個名為_init_.py的文件.該文件內(nèi)容可以為空.這個層次結(jié)構(gòu)如下所示:pare nt-_i nit_.py-child可以將之打印岀來通常我們可以將module的包路徑放到環(huán)境變量PYTHONPATH 中,該環(huán)境變量會自動添加到sys.path 屬性.另一種方便的方法是編程中直接指定我們的module路徑到sys.path 中:import syssys.path.appe
溫馨提示
- 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)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 自體免疫性疾病研究體系
- 急診創(chuàng)傷病人麻醉處理要點
- 2025年新高考數(shù)學(xué)一輪復(fù)習(xí)講義:第九章統(tǒng)計與成對數(shù)據(jù)的統(tǒng)計分析(學(xué)生版)
- 2025年音樂版權(quán)運營案例分析:流媒體平臺用戶付費策略深度研究報告
- 基于2025年標(biāo)準(zhǔn)的學(xué)校體育館建設(shè)初步設(shè)計抗震性能評估報告
- 房地產(chǎn)企業(yè)2025年財務(wù)風(fēng)險管理策略與穩(wěn)健經(jīng)營路徑研究優(yōu)化優(yōu)化優(yōu)化優(yōu)化報告
- 2025年森林生態(tài)系統(tǒng)服務(wù)功能評估在生態(tài)修復(fù)中的應(yīng)用報告
- 2025年能源互聯(lián)網(wǎng)背景下分布式能源交易策略研究報告
- 一番的意思4篇
- 書法培訓(xùn)班教學(xué)管理制度
- 2025年甘肅高考物理試卷真題及答案詳解(精校打印版)
- 2025至2030中國工業(yè)電機行業(yè)市場發(fā)展現(xiàn)狀及商業(yè)模式與投資發(fā)展報告
- 部編人教版小學(xué)語文1-6年級詞語表
- 測繪類技術(shù)設(shè)計管理制度
- 中醫(yī)艾灸盒課件下載
- 浙江省溫州市名校2025屆七下數(shù)學(xué)期末考試試題含解析
- 《鐵路旅客運輸組織(活頁式)》課件 7.3 旅客傷害應(yīng)急處置
- 公司合同月結(jié)協(xié)議書
- 2025年海綿項目評估報告
- 農(nóng)村生活污水治理專項施工方案
- GB/T 45545-2025廚房家具配合尺寸
評論
0/150
提交評論