




版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領
文檔簡介
1、Python入門教程 超詳細1小時學會Python本文適合有經驗的程序員盡快進入Python世界.特別地,如果你掌握Java和Javascript,不用1小時你就可以用Python快速流暢地寫有用的Python程序.為什么使用Python 假設我們有這么一項任務:簡單測試局域網中的電腦是否連通.這些電腦的ip范圍從192.168.0.101到192.168.0.200. 思路:用shell編程.(Linux通常是bash而Windows是批處理腳本).例如,在Windows上用ping
2、ip 的命令依次測試各個機器并得到控制臺輸出.由于ping通的時候控制臺文本通常是"Reply from . " 而不通的時候文本是"time out . " ,所以,在結果中進行字符串查找,即可知道該機器是否連通. 實現:Java代碼如下:String cmd="cmd.exe ping "String ipprefix="192.168.10."int begin=101;int end=200;Process
3、60;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.
4、getInputStream(); while(line = reader.readLine() != null) /Handling line , may logs it.
5、160;reader.close(); p.destroy(); 這段代碼運行得很好,問題是為了運行這段代碼,你還需要做一些額外的工作.這些額外的工作包括:1. 編寫一個類文件2. 編寫一個main方法3. 將之編譯成字節代碼4. 由于字節代碼不能直接運行,你需要再寫個小小的bat或者bash腳本來運行. 當然,用C/C+同樣能完成這項工作.但C/C+不是跨平臺語言.在這個足夠簡單的例子中也許看不出C/C+和Java實現的區別,但在一些更為復雜的場景,比如要將連通與否的信息記錄
6、到網絡數據庫.由于Linux和Windows的網絡接口實現方式不同,你不得不寫兩個函數的版本.用Java就沒有這樣的顧慮. 同樣的工作用Python實現如下:import subprocesscmd="cmd.exe"begin=101end=200while begin<end: p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE, &
7、#160; stdin=subprocess.PIPE, stderr=subprocess.PIPE) p.stdin.write("ping 192.168.1.
8、"+str(begin)+"n") p.stdin.close() p.wait() print "execution result: %s"%p.stdout.read() 對比Java,Python的實現更為簡潔,你編寫的時間更快.你不需要寫main函數,并且這個程序保存之后可以直接運行.另外,和Java一樣,Python也是跨平臺的.
9、160; 有經驗的C/Java程序員可能會爭論說用C/Java寫會比Python寫得快.這個觀點見仁見智.我的想法是當你同時掌握Java和Python之后,你會發現用Python寫這類程序的速度會比Java快上許多.例如操作本地文件時你僅需要一行代碼而不需要Java的許多流包裝類.各種語言有其天然的適合的應用范圍.用Python處理一些簡短程序類似與操作系統的交互編程工作最省時省力.Python應用場合 足夠簡單的任務,例如一些shell編程.如果你喜歡用Python設計大型商業網站或者設計復雜的游戲,悉聽尊便.2 快速入門2.1 H
10、ello world 安裝完Python之后(我本機的版本是2.5.4),打開IDLE(Python GUI) , 該程序是Python語言解釋器,你寫的語句能夠立即運行.我們寫下一句著名的程序語句:print "Hello,world!" 并按回車.你就能看到這句被K&R引入到程序世界的名言. 在解釋器中選擇"File"-"New Window" 或快捷鍵 Ctrl+N , 打開一個新的編輯器.寫下如下語句:
11、print "Hello,world!"raw_input("Press enter key to close this window"); 保存為a.py文件.按F5,你就可以看到程序的運行結果了.這是Python的第二種運行方式. 找到你保存的a.py文件,雙擊.也可以看到程序結果.Python的程序能夠直接運行,對比Java,這是一個優勢.2.2 國際化支持 我們換一種方式
12、來問候世界.新建一個編輯器并寫如下代碼:print "歡迎來到奧運中國!"raw_input("Press enter key to close this window"); 在你保存代碼的時候,Python會提示你是否改變文件的字符集,結果如下:# -*- coding: cp936 -*- print "歡迎來到奧運中國!"raw_input("Press enter key&
13、#160;to close this window"); 將該字符集改為我們更熟悉的形式:# -*- coding: GBK -*- print "歡迎來到奧運中國!" # 使用中文的例子raw_input("Press enter key to close this window"); 程序一樣運行良好.2.3 方便易用的計算器
14、 用微軟附帶的計算器來計數實在太麻煩了.打開Python解釋器,直接進行計算:a=100.0b=201.1c=2343print (a+b+c)/c2.4 字符串,ASCII和UNICODE 可以如下打印出預定義輸出格式的字符串:print """Usage: thingy OPTIONS -h
15、0; Display this usage message -H hostname Hostname to connect to""
16、" 字符串是怎么訪問的?請看這個例子:word="abcdefg"a=word2print "a is: "+ab=word1:3print "b is: "+b # index 1 and 2 elements of word.c=word:2print "c is: "+c #
17、index 0 and 1 elements of word.d=word0:print "d is: "+d # All elements of word.e=word:2+word2:print "e is: "+e # All elements of word.f=word-1print "f is:&
18、#160;"+f # The last elements of word.g=word-4:-2print "g is: "+g # index 3 and 4 elements of word.h=word-2:print "h is: "+h # The last two elements.i=
19、word:-2print "i is: "+i # Everything except the last two charactersl=len(word)print "Length of word is: "+ str(l) 請注意ASCII和UNICODE字符串的區別:print "Input your Chinese
20、 name:"s=raw_input("Press enter to be continued");print "Your name is : " +s;l=len(s)print "Length of your Chinese name in asc codes is:"+str(l);a=unicode(s,&q
21、uot;GBK")l=len(a)print "I'm sorry we should use unicode char!Characters number of your Chinese name in unicode is:"+str(l);2.5 使用List 類似Java里的List,這是一種方便易用的數據類型:word='a','b'
22、;,'c','d','e','f','g'a=word2print "a is: "+ab=word1:3print "b is: "print b # index 1 and 2 elements of word.c=word:2print "c is: "print
23、;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
24、=word-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: "
25、;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(l)print &
26、quot;Adds new element"word.append('h')print word2.6 條件和循環語句# Multi-way decisionx=int(raw_input("Please enter an integer:")if x<0: x=0 print "Negative changed to
27、60;zero"elif x=0: print "Zero"else: print "More"# Loops Lista = 'cat', 'window', 'defenestrate'for x in a: print x,
28、160;len(x)2.7 如何定義函數# Define and invoke function.def sum(a,b): return a+bfunc = sumr = func(5,6)print r# Defines function with default argumentdef add(a,b=2): return
29、0;a+br=add(1)print rr=add(1,5)print r 并且,介紹一個方便好用的函數:# The range() functiona =range(5,10)print aa = range(-2,-7)print aa = range(-7,-2)print aa = range(-2,-11,-3) # The 3rd parameter
30、;stands for stepprint a2.8 文件I/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("First line
31、60;2.")f.close()f=open(spath,"r") # Opens file for readingfor line in f: print linef.close()2.9 異常處理s=raw_input("Input your age:")if s ="": raise Exc
32、eption("Input must no be empty.")try: i=int(s)except ValueError: print "Could not convert data to an integer."except: print "Unknown exc
33、eption!"else: # It is useful for code that must be executed if the try clause does not raise an exception print "You are %d" % i," y
34、ears old"finally: # Clean up action print "Goodbye!"2.10 類和繼承class Base: def _init_(self): self.data = def add(se
35、lf, x): self.data.append(x) def addtwice(self, x): self.add(x) self.add(x)# Child extends Baseclass C
36、hild(Base): def plus(self,a,b): return a+boChild =Child()oChild.add("str1")print oChild.dataprint oChild.plus(2,3)2.11 包機制 每一個.py文件稱為一個module,module之間可以互相導入.請參看以下例子:# a.pyd
37、ef add_func(a,b): return a+b# b.pyfrom a import add_func # Also can be : import aprint "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定義包的方式稍微有點古怪,假設我們有一個parent文件夾,該文件夾有一個chil
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯系上傳者。文件的所有權益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網頁內容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
- 4. 未經權益所有人同意不得將文件中的內容挪作商業或盈利用途。
- 5. 人人文庫網僅提供信息存儲空間,僅對用戶上傳內容的表現方式做保護處理,對用戶上傳分享的文檔內容本身不做任何修改或編輯,并不能對任何下載內容負責。
- 6. 下載文件中如有侵權或不適當內容,請與我們聯系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 2025年數字藝術與設計課程考試卷及答案
- 2025年護理學專業畢業生實習考試試題及答案
- 2025年大數據分析師職業資格考試試題及答案
- 2025年房地產業務管理綜合考核試卷及答案
- 屋頂裝修協議書范本
- 早教工作總結匯報
- 秦俑創新美術課件
- 蠶桑養殖培訓講座
- 腫瘤病例診療經過圖
- 胃癌患者的防治與護理
- 中藥煎藥室應急預案
- 華東師大版七年級數學上冊教學課件
- 中國航天(航天科普知識)PPT
- GB/T 27806-2011環氧瀝青防腐涂料
- GB/T 17949.1-2000接地系統的土壤電阻率、接地阻抗和地面電位測量導則第1部分:常規測量
- 夢幻西游古龍服務端安裝教程
- 《出生醫學證明》單親母親情況聲明
- 4配電柜安全風險點告知牌
- 旋挖機操作手知識試卷含參考答案
- Q∕GDW 11445-2015 國家電網公司管理信息系統安全基線要求
- 材料科學基礎 第2章 晶體結構
評論
0/150
提交評論