Python入門教程超詳細(xì)1小時學(xué)會Python_第1頁
Python入門教程超詳細(xì)1小時學(xué)會Python_第2頁
Python入門教程超詳細(xì)1小時學(xué)會Python_第3頁
已閱讀5頁,還剩8頁未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

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

文檔簡介

1、Python入門教程超詳細(xì)1小時學(xué)會Python為什么使用Pytho n假設(shè)我們有這么一項(xiàng)任務(wù):簡單測試局域網(wǎng)中的電腦是否連通這些電腦的ip范圍從 192.168.0.101 到 192.168.0.200.思路:用shell編程.Linux 通常是bash而Windows是批處理腳本.例如,在 Windows上用ping ip的命令依次測試各個機(jī)器并得到控制臺輸出.由于ping通的時候控制臺文本通常是"Reply from ."而不通的時候文本是"time out .", 所以,在結(jié)果中進(jìn)行字符串查找,即可知道該機(jī)器是否連通.實(shí)現(xiàn):Java代碼如下:S

2、tring 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 lnputStreamReader(p.getlnputStream();while (line =

3、reader.readLine() != null )/Handling line , may logs it.reader.close();p.destroy();這段代碼運(yùn)行得很好,問題是為了運(yùn)行這段代碼,你還需要做一些額外的工作這些額外的工作包括:1. 編寫一個類文件2. 編寫一個main方法3. 將之編譯成字節(jié)代碼4. 由于字節(jié)代碼不能直接運(yùn)行,你需要再寫個小小的bat或者bash腳本來運(yùn)行.當(dāng)然,用C/C+同樣能完成這項(xiàng)工作.但C/C+不是跨平臺語言.在這個足夠簡單的例 子中也許看不出 C/C+和 Java實(shí)現(xiàn)的區(qū)別,但在一些更為復(fù)雜的場景,比方要將連通與否的 信息記錄到網(wǎng)絡(luò)數(shù)據(jù)庫.

4、由于Linux和Windows的網(wǎng)絡(luò)接口實(shí)現(xiàn)方式不同,你不得不寫兩個函 數(shù)的版本.用Java就沒有這樣的顧慮.同樣的工作用Python實(shí)現(xiàn)如下:import subprocesscmd="cmd.exe"begin=101end=200while beginvend:p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stdin=subprocess.PIPE, stderr=subprocess.PIPE)p.stdin.write("ping192.168.1."+str(begin)+&

5、quot;n")p.stdin.close()p.wait()比照J(rèn)ava,Python的實(shí)現(xiàn)更為簡潔,你編寫的時間更快你不需要寫main函數(shù),并且 這個程序保存之后可以直接運(yùn)行另外,和Java 樣,Python也是跨平臺的有經(jīng)驗(yàn)的C/Java程序員可能會爭論說用C/Java寫會比Python寫得快.這個觀點(diǎn)見仁見智我的想法是當(dāng)你同時掌握J(rèn)ava和Python之后,你會發(fā)現(xiàn)用Python寫這類程序的速度會比Java快上許多.例如操作本地文件時你僅需要一行代碼而不需要Java的許多流包裝類.各種語言有其天然的適合的應(yīng)用范圍用Python處理一些簡短程序類似與操作系統(tǒng)的交互編程工作最省時

6、省力Python應(yīng)用場合足夠簡單的任務(wù),例如一些shell編程如果你喜歡用Python設(shè)計大型商業(yè)網(wǎng)站或者設(shè)計復(fù)雜的游戲,悉聽尊便2快速入門2.1 Hello world安裝完P(guān)ython之后(我本機(jī)的版本是 254),翻開IDLE(Python GUI), 該程序是Python語言解釋器,你寫的語句能夠立即運(yùn)行我們寫下一句著名的程序語句:print "Hello,world!"并按回車.你就能看到這句被 K&R引入到程序世界的名言在解釋器中選擇"File"-"New Window" 或快捷鍵Ctrl+N ,翻開一個新的編輯器

7、寫下如下語句print "Hello,world!"raw_input("Press enter key to close thiswindow.");保存為a.py文件.按F5,你就可以看到程序的運(yùn)行結(jié)果了.這是Python的第二種運(yùn)行方式.找到你保存的a.py文件,雙擊.也可以看到程序結(jié)果.Python的程序能夠直接運(yùn)行 比照J(rèn)ava,這是一個優(yōu)勢.2.2國際化支持我們換一種方式來問候世界.新建一個編輯器并寫如下代碼print"歡送來到奧運(yùn)中國!"raw_input("Press enter key to close t

8、hiswindow");在你保存代碼的時候,Python會提示你是否改變文件的字符集,結(jié)果如下:# -*- codi ng: cp936 -*-print"歡送來到奧運(yùn)中國!"raw_input("Press enter key to close thiswindow");將該字符集改為我們更熟悉的形式:# -*- cod ing: GBK -*-程序一樣運(yùn)行良好2.3方便易用的計算器用微軟附帶的計算器來計數(shù)實(shí)在太麻煩了翻開Python解釋器,直接進(jìn)行計算a=100.02.4 字符串,ASCII 和 UNICODE可以如下打印出預(yù)定義輸出格式的

9、字符串printUsage: thingy OPTIONS-h-H hostnameDisplay this usage messageHostname to connect to字符串是怎么訪問的?請看這個例子word="abcdefg"a=word2 b=word1:3print"b is:"+b#index1 and 2 elements ofword.c=word:2print"c is:"+c#index0and 1 elements ofword.d=word0:print"d is:"+d#Allel

10、ements of word.e=word:2+word2:print"e is:"+e#Allelements of word.f=word-1print"f is:"+f#Thelastelements of word.g=word-4:-2print"g is:"+g#index3and 4 elements ofword.h=word-2:print"h is:"+h#Thelasttwo elements.i=word:-2print"i is:"+i#Everythingexcept

11、 the lasttwo charactersl=len(word)print"Lengthofwordis:"+str(l)請注意ASCII和UNICODE字符串的區(qū)別:print"InputyourChinesename:"s=raw_input("Pressenter tobecontinued ");print"Your nameis-n+s;l=len(s)print"LengthofyourChinesename in asc codesis:"+str(l);a=unicode(s,&quo

12、t;GBK")I=len(a)Chinese print "I'm sorry we should use unicode char!Characters number of your name in unicode is :"+str(l);2.5 使用 List類似Java里的List,這是一種方便易用的數(shù)據(jù)類型word='a','b','c','d','e','f','g'a=word2print"ais:"+ab=wo

13、rd1:3print"bis:"print b # index 1 and 2 elements of word. c=word:2print "c is: "print c # index 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=word-1print f # The las

14、t elements of word.g=word-4:-2print "g is: "print g # index 3 and 4 elements of word.h=word-2:print"his: "printh# Thelast two elements.i=word:-2print"iis: "print i # Everything except the last two charactersl=len(word)print"Lengthofwordis:"+ str(l)print"A

15、ddsnewelement"word.append('h')printword2.6條件和循環(huán)語句# Multi-way decisionx=int (raw_input("Please enter an integer:")if x<0:x=0print"Negativechanged to zero"elif x=0:print"Zero"else :# Loops Lista = 'cat','window','defenestrate'for x

16、in a:printx, len(x)2.7如何定義函數(shù)# Define and invoke function.def sum(a,b):return a+bdef add(a,b=2):return a+br=add(1)printrr=add(1,5)printr并且,介紹一個方便好用的函數(shù)# The range() functiona =range(5,10)a = range(_2,_7)printa a = range(-7,-2)printaa = range(-2,-11,-3)# The 3rd parameter stands for stepprinta2.8文件I/Os

17、path="D:/download/baa.txt"f=open(spath,"w") # Opens file for writing.Creates this file doesn't exist. f.write("Firstline 1.n")f.writelines("Firstline 2.")f.close()f=open(spath,"r") # Opens file for readingfor line in f:print linef.close()2.9異常處理s

18、=raw_input("Input your age:")if s ="":raise Exception("lnputmust no be empty.")try : except ValueError:print"Could not convertdata to an integer."except:print"Unknown exception!"does nelse :# It is useful for code that must be executed if the try cla

19、useot 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(Base):def pl

20、us(self,a,b):return a+boChild =Child() oChild.add("str1")printoChild.dataprintoChild.plus(2,3)2.11包機(jī)制每一個.py文件稱為一個module,module之間可以互相導(dǎo)入.請參看以下例子# a.pydef add_func(a,b):return a+b# b.pyfrom a import add_func # Also can be : import aprint"Import add_func frommodule a"print"Resul

21、t of 1 plus 2is:"printadd_func(1,2)#If using "import a", then here should be "a.add_func"module可以定義在包里面.Python定義包的方式稍微有點(diǎn)乖僻,假設(shè)我們有一個par ent文件夾,該文件夾有一個 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的包路徑.你可以將之打印出來:import sysprint sys.path通常我們可以將 module的包路徑放到環(huán)境變量PYTHONPATH,該環(huán)境變量

溫馨提示

  • 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

提交評論