1 為什麼要使用Python?
假設我們有這麼一項任務:簡單測試局域網中的電腦是否連通.這些電腦的ip範圍從192.168.0.101到192.168.0.200.
想法:用shell編程.(Linux通常是bash而Windows是批次腳本).例如,在Windows上用ping ip 的命令依次測試各個機器並得到控制台輸出.由於ping通的時候控制台文本通常是"Reply from ... " 而不通的時候文字是"time out ... " ,所以,在結果中進行字串查找,即可知道該機器是否連通.
實作:Java程式碼如下:
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.getInputStream())); while((line = reader.readLine()) != null) { //Handling line , may logs it. } reader.close(); p.destroy(); }
這段程式碼運作得很好,問題是為了運行這段程式碼,你還需要做一些額外的工作.這些額外的工作包括:
#寫一個類別檔案
寫一個main方法
將之編譯成位元組程式碼
由於字節程式碼不能直接運作,你需要再寫一個小小的bat或bash腳本來運行.
當然,用C/C++同樣能完成這項工作.但C/C++不是跨平台語言.在這個足夠簡單的例子中也許看不出C/C++和Java實現的區別,但在一些更為複雜的場景,比如要將連通與否的資訊記錄到網路資料庫.由於Linux和Windows的網路介面實作方式不同,你不得不寫兩個函數的版本.用Java就沒有這樣的顧慮.
同樣的工作用Python實現如下:
import subprocess cmd="cmd.exe" begin=101 end=200 while begin<end: p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE) p.stdin.write("ping 192.168.1."+str(begin)+"\n") p.stdin.close() p.wait() print "execution result: %s"%p.stdout.read()
對比Java,Python的實現更為簡潔,你編寫的時間更快.你不需要寫main函數,並且這個程式保存之後可以直接運行.另外,和Java一樣,Python也是跨平台的.
有經驗的C/Java程式設計師可能會爭論說用C/Java寫會比Python寫得快.這個觀點見仁見智.我的想法是當你同時掌握Java和Python之後,你會發現用Python寫這類程式的速度會比Java快上許多.例如操作本地文件時你僅需要一行程式碼而不需要Java的許多串流包裝類別.各種語言有其天然的適合的應用範圍.用Python處理一些簡短程式類似與作業系統的互動程式設計工作最省時省力.
Python應用場合
足夠簡單的任務,例如一些shell程式設計.如果你喜歡用Python設計大型商業網站或設計複雜的遊戲,悉聽尊便.
2 快速入門
2.1 Hello world
安裝完Python之後(我本機的版本是2.5.4),打開IDLE(Python GUI) , 該程式是Python語言解釋器,你寫的語句能夠立即運行.我們寫下一句著名的程式語句:
##
print "Hello,world!"
並按回車.你就能看到這句被K&R引入到程式世界的名言.
在解釋器中選擇"File"--"New Window" 或快捷鍵Ctrl+N , 開啟一個新的編輯器.寫下如下語句:
print "Hello,world!" raw_input("Press enter key to close this window");
儲存為a.py檔.按F5,你就可以看到程式的運作結果了.這是Python的第二種運作方式.
找到你保存的a.py檔案,雙擊.也可以看到程式結果.Python的程式能夠直接運作,對比Java,這是一個優點.
2.2 國際化支援 我們換個方式來問候世界.新建一個編輯器並寫如下程式碼:
print "欢迎来到奥运中国!" raw_input("Press enter key to close this window");# 在你儲存程式碼的時候,Python會提示你是否改變文件的字符集,結果如下:
# -*- coding: cp936 -*- print "欢迎来到奥运中国!" raw_input("Press enter key to close this window");
將該字符集改為我們更熟悉的形式:
#
# -*- coding: GBK -*- print "欢迎来到奥运中国!" # 使用中文的例子 raw_input("Press enter key to close this window");
程式一樣運作良好.
2.3 方便易用的計算器
a=100.0 b=201.1 c=2343 print (a+b+c)/c
2.4 字串,ASCII和UNICODE
可以如下列印出預先定義輸出格式的字串:
print """ Usage: thingy [OPTIONS] -h Display this usage message -H hostname Hostname to connect to """
字串是怎麼存取的?請看這個範例:
word="abcdefg" a=word[2] print "a is: "+a b=word[1:3] print "b is: "+b # index 1 and 2 elements of word. c=word[:2] print "c is: "+c # index 0 and 1 elements of word. d=word[0:] print "d is: "+d # All elements of word. e=word[:2]+word[2:] print "e is: "+e # All elements of word. f=word[-1] print "f is: "+f # The last elements of word. g=word[-4:-2] print "g is: "+g # index 3 and 4 elements of word. h=word[-2:] print "h is: "+h # The last two elements. i=word[:-2] print "i is: "+i # Everything except the last two characters l=len(word) print "Length of word is: "+ str(l)請注意ASCII和UNICODE字串的差異:
print "Input your Chinese 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,"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
資料型別:
#
word=['a','b','c','d','e','f','g'] a=word[2] print "a is: "+a b=word[1:3] print "b is: " print b # index 1 and 2 elements of word. c=word[:2] print "c is: " print c # index 0 and 1 elements of word. d=word[0:] print "d is: " print d # All elements of word. e=word[:2]+word[2:] print "e is: " print e # All elements of word. f=word[-1] print "f is: " print f # The last elements of word. g=word[-4:-2] print "g is: " print g # index 3 and 4 elements of word. h=word[-2:] print "h is: " print h # The last two elements. i=word[:-2] print "i is: " print i # Everything except the last two characters l=len(word) print "Length of word is: "+ str(l) print "Adds new element" word.append('h') print word
2.6 條件與循環語句
# Multi-way decision
x=int(raw_input("Please enter an integer:"))
if x<0:
x=0
print "Negative changed to zero"
elif x==0:
print "Zero"
else:
print "More"
# Loops List
a = ['cat', 'window', 'defenestrate']
for x in a:
print x, len(x)
#2.7 如何定義函數
# Define and invoke function.
def sum(a,b):
return a+b
func = sum
r = func(5,6)
print r
# Defines function with default argument
def add(a,b=2):
return a+b
r=add(1)
print r
r=add(1,5)
print r
並且,介紹一個方便好用的函數:
# The range() function a =range(5,10) print a a = range(-2,-7) print a a = range(-7,-2) print a a = range(-2,-11,-3) # The 3rd parameter stands for step print a
2.8 文件I/O
spath="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 2.") f.close() f=open(spath,"r") # Opens file for reading for line in f: print line f.close()
2.9 异常处理
s=raw_input("Input your age:") if s =="": raise Exception("Input must no be empty.") try: i=int(s) except ValueError: print "Could not convert data to an integer." except: print "Unknown exception!" else: # It is useful for code that must be executed if the try clause does not raise an exception print "You are %d" % i," years old" finally: # Clean up action print "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 Base class Child(Base): def plus(self,a,b): return a+b oChild =Child() oChild.add("str1") print oChild.data print oChild.plus(2,3)
2.11 包机制
每一个.py文件称为一个module,module之间可以互相导入.请参看以下例子:
# a.py def add_func(a,b): return a+b
# b.py from a import add_func # Also can be : import a print "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文件夹,该文件夹有一个child子文件夹.child中有一个module a.py . 如何让Python知道这个文件层次结构?很简单,每个目录都放一个名为_init_.py 的文件.该文件内容可以为空.这个层次结构如下所示:
parent --init_.py --child -- init_.py --a.py b.py
那么Python如何找到我们定义的module?在标准包sys中,path属性记录了Python的包路径.你可以将之打印出来:
import sys print sys.path
通常我们可以将module的包路径放到环境变量PYTHONPATH中,该环境变量会自动添加到sys.path属性.另一种方便的方法是编程中直接指定我们的module路径到sys.path 中:
import sys sys.path.append('D:\\download') from parent.child.a import add_func print sys.path print "Import add_func from module a" print "Result of 1 plus 2 is: " print add_func(1,2)
总结
你会发现这个教程相当的简单.许多Python特性在代码中以隐含方式提出,这些特性包括:Python不需要显式声明数据类型,关键字说明,字符串函数的解释等等.我认为一个熟练的程序员应该对这些概念相当了解,这样在你挤出宝贵的一小时阅读这篇短短的教程之后,你能够通过已有知识的迁移类比尽快熟悉Python,然后尽快能用它开始编程.
当然,1小时学会Python颇有哗众取宠之嫌.确切的说,编程语言包括语法和标准库.语法相当于武术招式,而标准库应用实践经验则类似于内功,需要长期锻炼.Python学习了Java的长处,提供了大量极方便易用的标准库供程序员"拿来主义".(这也是Python成功的原因),在开篇我们看到了Python如何调用Windows cmd的例子,以后我会尽量写上各标准库的用法和一些应用技巧,让大家真正掌握Python.
以上是為什麼用Python及Python快速入門教程的詳細內容。更多資訊請關注PHP中文網其他相關文章!

Python不是嚴格的逐行執行,而是基於解釋器的機制進行優化和條件執行。解釋器將代碼轉換為字節碼,由PVM執行,可能會預編譯常量表達式或優化循環。理解這些機制有助於優化代碼和提高效率。

可以使用多種方法在Python中連接兩個列表:1.使用 操作符,簡單但在大列表中效率低;2.使用extend方法,效率高但會修改原列表;3.使用 =操作符,兼具效率和可讀性;4.使用itertools.chain函數,內存效率高但需額外導入;5.使用列表解析,優雅但可能過於復雜。選擇方法應根據代碼上下文和需求。

有多種方法可以合併Python列表:1.使用 操作符,簡單但對大列表不內存高效;2.使用extend方法,內存高效但會修改原列表;3.使用itertools.chain,適用於大數據集;4.使用*操作符,一行代碼合併小到中型列表;5.使用numpy.concatenate,適用於大數據集和性能要求高的場景;6.使用append方法,適用於小列表但效率低。選擇方法時需考慮列表大小和應用場景。

CompiledLanguagesOffersPeedAndSecurity,而interneterpretledlanguages provideeaseafuseanDoctability.1)commiledlanguageslikec arefasterandSecureButhOnderDevevelmendeclementCyclesclesclesclesclesclesclesclesclesclesclesclesclesclesclesclesclesclesandentency.2)cransportedeplatectentysenty

Python中,for循環用於遍歷可迭代對象,while循環用於條件滿足時重複執行操作。 1)for循環示例:遍歷列表並打印元素。 2)while循環示例:猜數字遊戲,直到猜對為止。掌握循環原理和優化技巧可提高代碼效率和可靠性。

要將列表連接成字符串,Python中使用join()方法是最佳選擇。 1)使用join()方法將列表元素連接成字符串,如''.join(my_list)。 2)對於包含數字的列表,先用map(str,numbers)轉換為字符串再連接。 3)可以使用生成器表達式進行複雜格式化,如','.join(f'({fruit})'forfruitinfruits)。 4)處理混合數據類型時,使用map(str,mixed_list)確保所有元素可轉換為字符串。 5)對於大型列表,使用''.join(large_li

pythonuseshybridapprace,ComminingCompilationTobyTecoDeAndInterpretation.1)codeiscompiledtoplatform-Indepententbybytecode.2)bytecodeisisterpretedbybythepbybythepythonvirtualmachine,增強效率和通用性。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

Safe Exam Browser
Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器

Atom編輯器mac版下載
最受歡迎的的開源編輯器

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)