1.面向的讀者:
具有Javascript經驗的程序猿。
2 快速入門
2.1 Hello world
安裝完Python之后,打開IDLE(Python GUI) , 該程序是Python語言解釋器,你寫的語句能夠立即運行.我們寫下一句著名的程序語句:
1 print "Hello,world!"
並按回車.你就能看到這句被K&R引入到程序世界的名言.
在解釋器中選擇"File"--"New Window" 或快捷鍵 Ctrl+N , 打開一個新的編輯器.寫下如下語句:
1 print "Hello,world!" 2 raw_input("Press enter key to close this window...");
保存為a.py文件.按F5,你就可以看到程序的運行結果了.這是Python的第二種運行方式.
找到你保存的a.py文件,雙擊.也可以看到程序結果.Python的程序能夠直接運行,對比Java,這是一個優勢.
2.2 國際化支持
我們換一種方式來問候世界.新建一個編輯器並寫如下代碼:
1 print "歡迎來到奧運中國!" 2 raw_input("Press enter key to close this window...");
在你保存代碼的時候,Python會提示你是否改變文件的字符集,結果如下:
1 # -*- coding: cp936 -*- 2 3 print "歡迎來到奧運中國!" 4 raw_input("Press enter key to close this window...");
將該字符集改為我們更熟悉的形式:
1 # -*- coding: GBK -*- 2 3 print "歡迎來到奧運中國!" # 使用中文的例子 4 raw_input("Press enter key to close this window...");
程序一樣運行良好.
2.3 方便易用的計算器
用微軟附帶的計算器來計數實在太麻煩了.打開Python解釋器,直接進行計算:
1 a=100.0 2 b=201.1 3 c=2343 4 print (a+b+c)/c
Python會自動幫你實現類型轉換。
2.4 字符串,ASCII和UNICODE
可以如下打印出預定義輸出格式的字符串:
1 print """ 2 Usage: Python 3 -Java 4 -C++ 5 """
結果輸出:
1 Usage: Python 2 -Java 3 -C++
字符串是怎么訪問的?請看這個例子:
1 word="abcdefg" // 數組 2 a=word[2] // 數組中的一個值 3 print "a is: "+a 4 b=word[1:3] // 數組范圍,取1到2的值,但是不取最后區間的值 5 print "b is: "+b # index 1 and 2 elements of word. 6 c=word[:2] // 數組范圍,從開始取到2,但是不取2的值 7 print "c is: "+c # index 0 and 1 elements of word. 8 d=word[0:] // 從頭開始取到尾 9 print "d is: "+d # All elements of word. 10 e=word[:2]+word[2:] // 繼續從頭取到尾 11 print "e is: "+e # All elements of word. 12 f=word[-1] // 取最后一個元素“g” 13 print "f is: "+f # The last elements of word. 14 g=word[-4:-2] // 倒着取,打印“de” 15 print "g is: "+g # index 3 and 4 elements of word. 16 h=word[-2:] // 倒着取,打印“fg” 17 print "h is: "+h # The last two elements. 18 i=word[:-2] // 倒着去,打印“abcde” 19 print "i is: "+i # Everything except the last two characters 20 l=len(word) // 長度,結果為7 21 print "Length of word is: "+ str(l)
請注意ASCII和UNICODE字符串的區別:
1 print "Input your Chinese name:" 2 s=raw_input("Press enter to be continued..."); 3 print "Your name is ... : " +s; 4 l=len(s) 5 print "Length of your Chinese name in asc codes is:"+str(l); 6 a=unicode(s,"GBK") 7 l=len(a) 8 print "I'm sorry we should use unicode char!Characters number of your Chinese \ 9 name in unicode is:"+str(l);
2.5 使用List
類似Java里的List,這是一種方便易用的數據類型:
1 word=['a','b','c','d','e','f','g'] 2 a=word[2] // a is: c 3 print "a is: "+a 4 b=word[1:3] 5 print "b is: " 6 print b # index 1 and 2 elements of word. // ['b', 'c'] 7 c=word[:2] 8 print "c is: " 9 print c # index 0 and 1 elements of word. // ['a', 'b'] 10 d=word[0:] 11 print "d is: " 12 print d # All elements of word. // ['a', 'b', 'c', 'd', 'e', 'f', 'g'] 13 e=word[:2]+word[2:] 14 print "e is: " 15 print e # All elements of word. // ['a', 'b', 'c', 'd', 'e', 'f', 'g'] 16 f=word[-1] 17 print "f is: " 18 print f # The last elements of word. // g 19 g=word[-4:-2] 20 print "g is: " 21 print g # index 3 and 4 elements of word. // ['d', 'e'] 22 h=word[-2:] 23 print "h is: " 24 print h # The last two elements. // ['f', 'g'] 25 i=word[:-2] 26 print "i is: " 27 print i # Everything except the last two characters // ['a', 'b', 'c', 'd', 'e'] 28 l=len(word) 29 print "Length of word is: "+ str(l) // 7 30 print "Adds new element..." 31 word.append('h') 32 print word // ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
2.6 條件和循環語句
1 # Multi-way decision 2 x=int(raw_input("Please enter an integer:")) 3 if x>0: 4 print "x>0" 5 elif x==0: 6 print "Zero" 7 else: 8 print "x<0"
while循環:
1 x=0 2 while (x<10): 3 print 'x is:', x // 需要特別注意的是:這里一定要縮進,不然會編譯不過 4 x+=1 5 6 print "end!"
for循環
1 words=['this','is','a','A'] 2 for word in words: 3 print word
提示:能使用for循環,就盡量不使用while循環
2.7 如何定義函數
1 def hello(name): 2 return 'hello ' + name + '!' 3 4 print hello('a')
並且,介紹一個方便好用的函數:
函數原型:range(start, end, scan):
參數含義:start:計數從start開始。默認是從0開始。例如range(5)等價於range(0, 5);
end:技術到end結束,但不包括end.例如:range(0, 5) 是[0, 1, 2, 3, 4]沒有5
scan:每次跳躍的間距,默認為1。例如:range(0, 5) 等價於 range(0, 5, 1)
1 >>> range(0, 8) 2 [0, 1, 2, 3, 4, 5, 6, 7] 3 >>> range(-5, -2) 4 [-5, -4, -3] 5 >>> range(-2, -5) 6 [] 7 >>> range(0, 6, 2) 8 [0, 2, 4]
我們再來試試麻煩的遞歸函數
1 def foo(i): 2 print 'the number is: ', i 3 i+=1 4 if i<10: 5 foo(i) 6 else: 7 print 'end!' 8 9 foo(0)
打印:
1 >>> 2 the number is: 0 3 the number is: 1 4 the number is: 2 5 the number is: 3 6 the number is: 4 7 the number is: 5 8 the number is: 6 9 the number is: 7 10 the number is: 8 11 the number is: 9 12 end!
2.8 文件I/O
1 spath="F:/1.txt" 2 f=open(spath,"w") # Opens file for writing.Creates this file doesn't exist. 3 f.write("First line 1.\n") 4 f.writelines("First line 2.") 5 f.close() // 1.txt 會被寫入上面兩行 6 7 f=open(spath,"r") # Opens file for reading 8 9 for line in f: 10 print line 11 12 f.close()
2.9 異常處理
1 s=raw_input("Input your age:") 2 if s =="": 3 raise Exception("Input must no be empty.") 4 try: 5 i=int(s) 6 except ValueError: 7 print "Could not convert data to an integer." 8 except: 9 print "Unknown exception!" 10 11 else: # It is useful for code that must be executed if the try clause does not raise an exception 12 print "You are ",s, "years old" 13 14 print "Goodbye!"
2.10 類和繼承
先看類的定義:
1 _metaclass_ = type 2 class Person: 3 def setName(self, name): 4 self.name = name 5 def getName(self): 6 return self.name 7 def greet(self): 8 print "hello, world. i am %s." % self.name 9 10 foo=Person() 11 bar=Person() 12 foo.setName('lucy') 13 bar.setName('lili') 14 15 foo.greet() 16 bar.greet()
為什么會有self呢?
在c++中,this指針是隱式的,除非不得以的時候,,比如傳進來的參數和類的成員變量的名字相同,或者要返回當前對象。 而python的self是顯示的。而且this指針基本上不用在函數頭里面。
python是動態語言,設計出來的類和靜態語言的格式不同,首先c++在類的定義(聲明)時,會指定類的成員變量,比如在private:里。但是Python不行,它沒法顯式的說 哪個屬性是自己的,而且屬性還可以動態的增加,此時,一個解決方案出來了,增加self,通過self.訪問的就可以做為類的屬性。至於類的方法為什么要顯式的寫上self(我感覺,完全可以由解釋器隱式添加上去),估計就是python的哲學導致的:Explicit is better than implicit.
接下里是繼承:
在python中繼承中的一些特點:
1:在繼承中基類的構造(__init__()方法)不會被自動調用,它需要在其派生類的構造中親自專門調用。
2:在調用基類的方法時,需要加上基類的類名前綴,且需要帶上self參數變量。區別於在類中調用普通函數時並不需要帶上self參數
3:Python總是首先查找對應類型的方法,如果它不能在派生類中找到對應的方法,它才開始到基類中逐個查找。(先在本類中查找調用的方法,找不到才去基類中找)。
1 # -*- coding: utf-8 -*- 2 _metaclass_ = type 3 class Fruit: 4 def __init__(self, color): 5 self.color = color 6 print "fruit's color: %s" % self.color 7 8 def grow(self): 9 print "grow..." 10 11 class Apple(Fruit): #繼承了父類 12 def __init__(self, color): #顯示調用父類的__init__方法 13 Fruit.__init__(self, color) 14 print "apple's color: %s" % self.color 15 16 class Banana(Fruit): #繼承了父類 17 def __init__(self, color): #顯示調用父類的__init__方法 18 Fruit.__init__(self, color) 19 print "banana's color:%s" % self.color 20 21 def grow(self): #覆蓋了父類的grow方法 22 print "banana grow..." 23 24 if __name__ == "__main__": 25 apple = Apple("red") 26 apple.grow() 27 banana = Banana("yellow") 28 banana.grow()
結果顯示:
1 >>> 2 fruit's color: red 3 apple's color: red 4 grow... 5 fruit's color: yellow 6 banana's color:yellow 7 banana grow...
2.11 包機制
每一個.py文件稱為一個module,module之間可以互相導入.請參看以下例子:
1 # a.py 2 def add_func(a,b): 3 return a+b
1 # b.py 2 from a import add_func # Also can be : import aprint "Import add_func from module a" 3 print "Result of 1 plus 2 is: " 4 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 的文件.該文件內容可以為空.這個層次結構如下所示:
1 parent 2 --__init_.py 3 --child 4 -- __init_.py 5 --a.pyb.py
那么Python如何找到我們定義的module?在標准包sys中,path屬性記錄了Python的包路徑.你可以將之打印出來:
1 import sys 2 print sys.path
通常我們可以將module的包路徑放到環境變量PYTHONPATH中,該環境變量會自動添加到sys.path屬性.另一種方便的方法是編程中直接指定我們的module路徑到sys.path 中:
1 import sys 2 sys.path.append('D:\\download')from parent.child.a import add_func 3 4 print sys.path 5 6 print "Import add_func from module a" 7 print "Result of 1 plus 2 is: " 8 print add_func(1,2)
總結
你會發現這個教程相當的簡單.許多Python特性在代碼中以隱含方式提出,這些特性包括:Python不需要顯式聲明數據類型,關鍵字說明,字符串函數的解釋等等.你能夠通過已有知識的遷移類比盡快熟悉Python,然后盡快能用它開始編程.