


下載本文檔
版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
1、實(shí)例教程:1小時(shí)學(xué)會(huì)Python1序言面向讀者本文適合有經(jīng)驗(yàn)的程序員盡快進(jìn)入Python2.x 世界.特別地,如果你掌握J(rèn)ava和Javascript,不用1小時(shí)你就可以用Python快速流暢地寫有用的 Python程序.Python3.x 用戶請(qǐng)參考:由于Django 不支持python3,所以為了你的開展?jié)摿?,建議你學(xué)習(xí)python2.x 為什么使用Pytho n假設(shè)我們有這么一項(xiàng)任務(wù):簡(jiǎn)單測(cè)試局域網(wǎng)中的電腦是否連通 .這些電腦的ipX圍從到192.168.0.200.思路:用shell編程.Linux 通常是bash而Windows 是批處理腳本.例如,在Windows 上用ping i
2、p的命令依次測(cè)試各個(gè)機(jī)器并得到控制臺(tái)輸出.由于ping通的時(shí)候控制臺(tái)文本通常是"Reply from ."而不通的時(shí)候文本是"time out .", 所以,在結(jié)果中進(jìn)行字符串查找,即可知道該機(jī)器是否連通. 實(shí)現(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();這段代碼運(yùn)行得很好,問題是為了運(yùn)行這段代碼,你還需要做一些額外的工作.這些額外的工作包括?編寫一個(gè)類文件?編寫一個(gè)main方法? 將之編譯成字節(jié)代碼?由
4、于字節(jié)代碼不能直接運(yùn)行,你需要再寫個(gè)小小的bat或者bash腳本來運(yùn)行.當(dāng)然,用C/C+同樣能完成這項(xiàng)工作.但C/C+不是跨平臺(tái)語言.在這個(gè)足夠簡(jiǎn)單的例子中也許看不 岀C/C+和Java實(shí)現(xiàn)的區(qū)別,但在一些更為復(fù)雜的場(chǎng)景,比方要將連通與否的信息記錄到網(wǎng)絡(luò)數(shù)據(jù)庫.由于Linux和Windows的網(wǎng)絡(luò)接口實(shí)現(xiàn)方式不同,你不得不寫兩個(gè)函數(shù)的版本.用Java就沒有這樣的顧慮. 同樣的工作用Python實(shí)現(xiàn)如下:比照J(rèn)ava,Python 的實(shí)現(xiàn)更為簡(jiǎn)潔,你編寫的時(shí)間更快.你不需要寫main函數(shù),并且這個(gè)程序保存之后 可以直接運(yùn)行.另外,和Java 樣,Python 也是跨平臺(tái)的.有經(jīng)驗(yàn)的C/Java
5、程序員可能會(huì)爭(zhēng)論說用C/Java寫會(huì)比Python寫得快.這個(gè)觀點(diǎn)見仁見智.我的想法是當(dāng)你同時(shí)掌握J(rèn)ava和Python之后,你會(huì)發(fā)現(xiàn)用Python寫這類程序的速度會(huì)比 Java快上許多.例如操作本地文件時(shí)你僅需要一行代碼而不需要Java的許多流包裝類.各種語言有其天然的適合的應(yīng)用X圍.用Python處理一些簡(jiǎn)短程序類似與操作系統(tǒng)的交互編程工作最省時(shí)省力.Pytho n應(yīng)用場(chǎng)合足夠簡(jiǎn)單的任務(wù),例如一些shell編程.如果你喜歡用Python設(shè)計(jì)大型商業(yè)或者設(shè)計(jì)復(fù)雜的游戲,悉聽尊便.2快速入門2.1 Hello world安裝完P(guān)ython之后(我本機(jī)的版本是2.5.4),翻開IDLE(Pyth
6、on GUI),該程序是Python語言解釋器,你寫的語句能夠立即運(yùn)行.我們寫下一句著名的程序語句:pri nt "Hello,world!"并按回車.你就能看到這句被K&R引入到程序世界的名言.在解釋器中選擇"File"-"NewWindow" 或快捷鍵Ctrl+N ,翻開一個(gè)新的編輯器.寫下如下語句:pri nt "Hello,world!"raw_input("Press enter key to close this windowL ");保存為a.py文件.按F5,你就可以看到
7、程序的運(yùn)行結(jié)果了.這是Python的第二種運(yùn)行方式. 找到你保存的a.py文件,雙擊.也可以看到程序結(jié)果.Python的程序能夠直接運(yùn)行,比照J(rèn)ava,這是一個(gè)優(yōu)勢(shì).2.2國際化支持我們換一種方式來問候世界.新建一個(gè)編輯器并寫如下代碼print "歡送來到奧運(yùn)中國!"raw_input("Press enter key to close this window-");在你保存代碼的時(shí)候,Python會(huì)提示你是否改變文件的字符集,結(jié)果如下:# -*- codi ng: cp936 -*- print "歡送來到奧運(yùn)中國!"raw_in
8、put("Press en ter key to close this wi ndow);將該字符集改為我們更熟悉的形式:# -*- cod ing: GBK -*-print "歡送來到奧運(yùn)中國!" #使用中文的例子raw_input("Press enter key to close this window");程序一樣運(yùn)行良好.2.3方便易用的計(jì)算器用微軟附帶的計(jì)算器來計(jì)數(shù)實(shí)在太麻煩了.翻開Python解釋器,直接進(jìn)行計(jì)算a=100.02.4 字符串,ASCII 和 UNICODE可以如下打印岀預(yù)定義輸岀格式的字符串print "
9、;"“Usage: thingy OPTIONS-hDisplay this usage message-H host nameHost name to conn ect tomill字符串是怎么訪問的?請(qǐng)看這個(gè)例子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)請(qǐng)注意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并且,介紹一個(gè)方便好用的函數(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 包機(jī)制每一個(gè).py文件稱為一個(gè)module,module之間可以互相導(dǎo)入.請(qǐng)參看以下例子# 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定義包的方式稍微有點(diǎn)乖僻,假設(shè)我們有一個(gè)parent文件夾,該文 件夾有一個(gè)child子文件夾.child中有一個(gè)module a.py . 如何讓Python知道這個(gè)文件層次結(jié)構(gòu) ?很簡(jiǎn) 單,每個(gè)目錄都放一個(gè)名為_init_.py的文件.該文件內(nèi)容可以為空.這個(gè)層次結(jié)構(gòu)如下所示:pare nt-_i nit_.py-child可以將之打印岀來通常我們可以將module的包路徑放到環(huán)境變量PYTHONPATH 中,該環(huán)境變量會(huì)自動(dòng)添加到sys.path 屬性.另一種方便的方法是編程中直接指定我們的module路徑到sys.path 中:import syssys.path.appe
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 物聯(lián)網(wǎng)芯片低功耗算法效率提升方法-洞察闡釋
- 端到端安全測(cè)試自動(dòng)化-洞察闡釋
- 中美美式文學(xué)中的文化多樣性體現(xiàn)與解讀-洞察闡釋
- 陰虛火旺與慢性免疫抑制的關(guān)聯(lián)性分析-洞察闡釋
- 綜合發(fā)展指標(biāo)研究
- 紅蔥頭在養(yǎng)殖尾水凈化中的效果與機(jī)理研究
- 高壓變電站智能化設(shè)計(jì)標(biāo)準(zhǔn)體系研究
- 軟件工程研究生的職業(yè)道路設(shè)計(jì)
- 城市公共設(shè)施綠色節(jié)能技術(shù)應(yīng)用研究
- 唐氏綜合征家族史護(hù)理
- 2025年天津市中考物理真題 (解析版)
- GA/T 2182-2024信息安全技術(shù)關(guān)鍵信息基礎(chǔ)設(shè)施安全測(cè)評(píng)要求
- 2025年北京市中考物理試題(解析版)
- 培訓(xùn)物業(yè)客服部禮儀禮節(jié)
- 北京海淀區(qū)一零一中學(xué)2025年八年級(jí)英語第二學(xué)期期末復(fù)習(xí)檢測(cè)模擬試題含答案
- 2025年廣東省高考生物試題(含答案解析)
- 院感知識(shí)手衛(wèi)生培訓(xùn)內(nèi)容
- 2025年 廣州市能源融資租賃有限公司招聘考試筆試試題附答案
- 章程規(guī)范業(yè)務(wù)管理制度
- QGDW11914-2018電力監(jiān)控系統(tǒng)網(wǎng)絡(luò)安全監(jiān)測(cè)裝置技術(shù)規(guī)范
- 新生兒洗澡及皮膚護(hù)理
評(píng)論
0/150
提交評(píng)論