




下載本文檔
版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡介
1、最新資料推薦Python入門教程超詳細(xì)1小時(shí)學(xué)會(huì)Python為什么使用Python假設(shè)我們有這么一項(xiàng)任務(wù):簡單測試局域網(wǎng)中的電腦是否連通.這些電腦的ip范圍從 192.168.0.101 到 192.168.0.200.思路:用shell編程.(Linux 通常是bash而Windows是批處理腳本).例如,在 Windo ws上用ping ip的命令依次測試各個(gè)機(jī)器并得到控制臺(tái)輸出.由于ping通的時(shí)候控制臺(tái)文本通常是"Reply from ."而不通的時(shí)候文本是"time out .", 所以,在結(jié)果中進(jìn)行字符串查找,即可知道該機(jī)器是否連通.實(shí)現(xiàn):J
2、ava代碼如下:String 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= Runtime.getRuntime().exec(cmd+i);String line = null ;BufferedReader reader = new BufferedReader( new InputStreamReader(p.getInputSt ream();while (l
3、ine = reader.readLine() != null )/Handling line , may logs it. reader.close();p.destroy();這段代碼運(yùn)行得很好,問題是為了運(yùn)行這段代碼,你還需要做一些額外的工作.這些額外的工作包括:1 .編寫一個(gè)類文件2 .編寫一個(gè)main方法3 .將之編譯成字節(jié)代碼4 .由于字節(jié)代碼不能直接運(yùn)行,你需要再寫個(gè)小小的bat或者bash腳本來運(yùn)行.當(dāng)然,用C/C+同樣能完成這項(xiàng)工作.但C/C+不是跨平臺(tái)語言.在這個(gè)足夠簡單的例 子中也許看不出 C/C+和Java實(shí)現(xiàn)的區(qū)別,但在一些更為復(fù)雜的場景,比如要將連通與否的 信息記錄
4、到網(wǎng)絡(luò)數(shù)據(jù)庫.由于Linux和Windows的網(wǎng)絡(luò)接口實(shí)現(xiàn)方式不同,你不得不寫兩個(gè)函 數(shù)的版本.用Java就沒有這樣的顧慮.同樣的工作用Python實(shí)現(xiàn)如下:import subprocesscmd="cmd.exe"begin=101end=200while begin<end:p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stdin=subprocess.PIPE,stderr=subprocess.PIPE)p.stdin.write("ping 192.168.1."+st
5、r(begin)+"n")p.stdin.close()p.wait()print "execution result:%s"%p.stdout.read()對(duì)比Java,Python的實(shí)現(xiàn)更為簡潔,你編寫的時(shí)間更快.你不需要寫main函數(shù),并且 這個(gè)程序保存之后可以直接運(yùn)行.另外,和Java 一樣,Python也是跨平臺(tái)的.有經(jīng)驗(yàn)的C/Java程序員可能會(huì)爭論說用C/Java寫會(huì)比Python寫得快.這個(gè)觀點(diǎn)見仁見智.我的想法是當(dāng)你同時(shí)掌握J(rèn)ava和Python之后,你會(huì)發(fā)現(xiàn)用Python寫這類程序的速度會(huì)比Java快上許多.例如操作本地文件時(shí)你僅需要
6、一行代碼而不需要Java的許多流包裝類.各種語言有其天然的適合的應(yīng)用范圍.用Python處理一些簡短程序類似與操作系統(tǒng)的交互編程工作最省時(shí)省力.Python應(yīng)用場合足夠簡單的任務(wù),例如一些shell編程.如果你喜歡用Python設(shè)計(jì)大型商業(yè)網(wǎng)站或者 設(shè)計(jì)復(fù)雜的游戲,悉聽尊便.2快速入門2.1 Hello world安裝完P(guān)ython之后(我本機(jī)的版本是 2.5.4),打開IDLE(Python GUI),該程序是Python語言解釋器,你寫的語句能夠立即運(yùn)行.我們寫下一句著名的程序語句:print "Hello,world!"并按回車.你就能看到這句被 K&R引入到
7、程序世界的名言在解釋器中選擇"File"-"New Window"或快捷鍵Ctrl+N ,打開一個(gè)新的編輯器寫下如下語句:print "Hello,world!"raw_input("Press enter key to close this window .");保存為a.py文件.按F5,你就可以看到程序的運(yùn)行結(jié)果了.這是Python的第二種運(yùn)行方式.找到你保存的a.py文件,雙擊.也可以看到程序結(jié)果.Python的程序能夠直接運(yùn)行 對(duì)比Java,這是一個(gè)優(yōu)勢.2.2 國際化支持我們換一種方式來問候世界.新建一
8、個(gè)編輯器并寫如下代碼:print "歡迎來到奧運(yùn)中國!"raw_input("Press enter key to close this window -");在你保存代碼的時(shí)候,Python會(huì)提示你是否改變文件的字符集,結(jié)果如下:# -*- coding: cp936 -*-print "歡迎來到奧運(yùn)中國!"raw_input("Press enter key to close this window -");將該字符集改為我們更熟悉的形式:# -*- coding: GBK -*-print "歡迎來
9、到奧運(yùn)中國!" # 使用中文的例子raw_input("Press enter key to close this window ");程序一樣運(yùn)行良好.2.3 方便易用的計(jì)算器用微軟附帶的計(jì)算器來計(jì)數(shù)實(shí)在太麻煩了.打開Python解釋器,直接進(jìn)行計(jì)算:13a=100.0 b=201.1 c=2343 print (a+b+c)/c2.4 字符串,ASCII 和 UNICODE可以如下打印出預(yù)定義輸出格式的字符串printUsage:thingy OPTIONS-h-H hostname字符串是怎么訪問的?請(qǐng)看這個(gè)例子:word="abcdefg&quo
10、t;a=word2print "a is: "+ab=word1:3Display this usage messageHostname to connect toprint "bis:"+bindex1 andelementsofword.c=word:2print "cis:+cindex0 andelementsofword.d=word0:print "dis:"+dAllelementsofword.e=word:2+word2:print "e is:+eAllelementsofword.f=word
11、-1print "f is:"+fThelastelementsof word.g=word-4:-2print "gis:+gindexand 4 elements ofword.h=word-2:print "his:"+hThelasttwo elements.i=word:-2print "iis:"+iEverythingexcept the lasttwo charactersl=len(word)printLengthof word is: "+ str(l)請(qǐng)注意ASCII和UNICOD亨符串的區(qū)別
12、print "Input your Chinese name:" s=raw_input("Press enter to be continued ,");print "Your name is :"+s;print "Length ofl=len(s) your Chinese name in asc codes is:"+str(l);a=unicode(s,"GBK")l=len(a)print "I'm sorry we should use unicode char!
13、Characters number of your Chinese name in unicode is :"+str(l);2.5 使用 List類似Java里的List,這是一種方便易用的數(shù)據(jù)類型word='a','b','c','d','e','f','g'a=word2 print "a is: "+ab=word1:3print"bis: "printb# index1andc=word:2print"cis: &
14、quot;printc# index0andd=word0:print"dis:"printd# Allelementse=word:2+word2:print"eis:"printe# Allelementsf=word-12 elements of word.1 elements of word.of word.of word.print "f is:printf # The lastelements of word.g=word-4:-2 print "g is:print g# indexand 4 elements of w
15、ord.h=word-2: print "h is:print h # The lasttwo elements.i=word:-2print "i is:print i # Everythingexcept the last two characters l=len(word) print "Length of word is: "+ str(l) print "Adds new elementword.append('h')print word2.6 條件和循環(huán)語句# Multi-way decisionx=int (raw
16、_input("Please enter an integer:")if x<0:x=0print"Negativechanged to zero"elif x=0:print"Zero"else :print "More"# Loops Lista = 'cat','window','defenestrate'for x in a:printx, len(x)2.7 如何定義函數(shù)# Define and invoke function.def sum(a,b)
17、: return a+bfunc = sumr = func(5,6)print r# Defines function with default argumentdef add(a,b=2): return a+br=add(1)printrr=add(1,5)printr并且,介紹一個(gè)方便好用的函數(shù):# The range() functiona =range(5,10)printaa=range(-2,-7)printaa=range(-7,-2)printaa=range(-2,-11,-3)# The 3rd parameter stands forstepprinta2.8 文件I
18、/Ospath="D:/download/baa.txt"f=open(spath,"w") # Opens file for writing.Creates this file doesn't exist.f.write("First line 1.n")f.writelines("Firstline 2.")f.close()f=open(spath,"r") # Opens file for readingfor line in f:print linef.close()2.9 異
19、常處理s=raw_input("Input your age:")if s ="":raise Exception("Inputmust no be empty.")try :i= int (s)except ValueError:print"Could not convertdata to an integer."except:print"Unknown exception!"else :# It is useful for code that must be executed if the
20、try clause doesot raise an exceptionprint"You are%d" % i," years old"finally :# Clean up actionprint"Goodbye!"2.10 類和繼承class Base:def_init_(self):self.data =def add(self, x):self.data.append(x)def addtwice(self, x):self.add(x)self.add(x)# Child extends Baseclass Child(B
21、ase):def plus(self,a,b):return a+boChild =Child()oChild.add("str1")printoChild.dataprintoChild.plus(2,3)2.11包機(jī)制每一個(gè).py文件稱為一個(gè)module,module之間可以互相導(dǎo)入.請(qǐng)參看以下例子# a.pydef add_func(a,b):return a+b# b.pyfrom a import add_func # Also can be : import aprint"Importadd_func frommodule a"print&q
22、uot;Resultof 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è)par ent文件夾,該文件夾有一個(gè) child子文件夾.child 中有一個(gè) module a.py . 如何讓 Python知道這個(gè)文件層次結(jié)構(gòu)?很簡單,每個(gè)目錄都放一個(gè)名為_init_.py 的文件.該文件內(nèi)容可以為空.這個(gè)層次結(jié)構(gòu)如下所示:parent-_init_.py-child- _init_.py-a.pyb.py那么Python如何找到我們定義的module?在標(biāo)準(zhǔn)包sys中,path屬性記錄了 Python的包路徑.你可以將之打印出來:import sysprint sys.path通常我
溫馨提示
- 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ì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 潮州供熱可行性研究報(bào)告
- 藥廠液體制劑監(jiān)控員工作總結(jié)模版
- 預(yù)防呼吸道傳染病
- 學(xué)前兒童發(fā)展 課件 第12章 學(xué)前兒童社會(huì)性的發(fā)展
- 婦幼健康計(jì)劃-婦幼健康計(jì)劃總結(jié)模版
- 業(yè)務(wù)員畢業(yè)生實(shí)習(xí)總結(jié)模版
- 2025年護(hù)士年度個(gè)人工作總結(jié)模版
- 大學(xué)生職業(yè)規(guī)劃大賽《生物科學(xué)專業(yè)》生涯發(fā)展展示
- 六班級(jí)的上學(xué)期美術(shù)組工作總結(jié)模版
- 英格瑪國企面試題目及答案
- 提水試驗(yàn)過程及數(shù)據(jù)處理
- (正式版)SHT 3046-2024 石油化工立式圓筒形鋼制焊接儲(chǔ)罐設(shè)計(jì)規(guī)范
- 呼吸系統(tǒng)(0001)課件
- 單位食堂美食節(jié)策劃方案
- 小學(xué)高段學(xué)生數(shù)學(xué)應(yīng)用意識(shí)培養(yǎng)的實(shí)踐研究 開題報(bào)告
- GA/T 2015-2023芬太尼類藥物專用智能柜通用技術(shù)規(guī)范
- 唱片行業(yè)前景分析
- 運(yùn)營經(jīng)理面試問題
- 醫(yī)美整形醫(yī)院渠道合作協(xié)議樣本
- 防刷單詐騙知識(shí)講座
- 《術(shù)前腸道準(zhǔn)備》課件
評(píng)論
0/150
提交評(píng)論