這不是給編程新手準備的教程,如果您入行編程不久,或者還沒有使用過1到2門編程語言,請移步!這是有一定編程經驗的人準備的.最好是熟知Java或C,懂得命令行,Shell等.總之,這是面向老鳥的,讓老鳥快速上手Python教程.
爲什麼總結這樣的一個教程
我雖不是老鳥,但已熟悉Java,C/C++, Shell和Perl,且對常見的數據結構和算法等都瞭解.最近因項目需要,要做一個小工具,評估後感覺用Python實現最爲方便,於是就有了對Python的學習.這時就需要一門快速上手Python的教程:因爲編程語言的基本知識,以及如何實現程序對我來說不是難事,關鍵的就是如何具體使用Python語句來體現程序的邏輯!Python的書籍對我來說內容太多了,沒有時間去看,查找也不是很容易!網上的資料又太零散,這就需要一個快速入門Python的教程.
這裏重點是以對比的方式來說明Python與其語言的不同之處,和一些Python特有的特性,以能以最快速度能用Python寫程序.
Python是一門動態語言
與Java,C等相對,Python不用編譯,像腳本一樣直接運行.這就導致了,所有錯誤都是運行時的!即使有語法錯誤,或者異常,如果程序邏輯沒有執行到,就不會有錯誤.比如一個if分支中有語法錯誤,使用了未定義的函數,但如果未執行到此分支,就可以正常運行.動態的另外一層意思就是它的類型是動態的,也就是說無需指定變量的類型,在運行時,根據它的內容來決定的類型.
如何運行Python
通常來講有二種方式,一種方式是交互式的,就像Shell命令行提示符那樣,交互式的,輸入,就有輸出;在終端輸入python命令,就進入了Python的命令提示符中:>>>輸入Python語句,解釋器就會執行,並輸出結果,如:
輸入exit()可以退出命令提示符.
- [alex@alexon:~]$python
- Python 2.7.3 (default, Apr 10 2013, 06:20:15)
- [GCC 4.6.3] on linux2
- Type "help", "copyright", "credits" or "license" for more information.
- >>> print 'hello, world'
- hello, world
- >>>
另外一種方式就是腳本,就像Shell的腳本的一樣,把一組命令集合到一起執行,這就能發揮更大的作用.
- #!/usr/bin/python
- print 'hello, world'
Python以縮進來區分語句塊
不像Java,C/C++以花括號{}來區分語句塊.Python是以縮進來表示語句塊,同一縮進級別爲同一級別的語句塊.一個腳本文件中的0級縮進是文件加載的時候就會被執行的語句,如上面的print.開啓一個新的縮進需要使用:(冒號),代表下一級別的語句塊,如條件,循環或者函數定義.
縮進最好使用四個空格.而且要注意縮進要一致,使用空格就全都用空格,使用Tab就都使用Tab,混用就可能得到縮進錯誤:
IndentationError: unindent does not match any outer indentation level
操作符
與Java和C中十分類似, +(加), -(減), *(乘), /(除), %(求餘), **(指數運算), = (賦值).以及減便運算,如 +=, -=, *=和/= 等.賦值運算與其他語言一致.
邏輯操作
> < <= >= != ==與其他語言一樣.
不一樣的有not邏輯非,and邏輯與和or邏輯或.
註釋與文檔
一行當中,從#開始地方就是註釋.不會影響下一行.""引號放在文件的開頭,函數的開頭或者一個類的開頭,就是文檔註釋,與Java中的/** ... */作用和目的是一樣的.
折行
如果一行太長了,寫不下了,就需要在下一行接着寫,這時可以使用\來告訴Python,下一行繼續.一行寫多個語句
Python是一個語句放在一行,行尾可以選擇性的加上;但如果想在一行放多個語句,就需要用;來分隔語句:a = 1; b = 2; c = 3;
雖然這在語法上可行,但不是一個好習慣,絕大多數的編程規範都是要一行寫一個語句.
基本數據類型
- int
- long
- bool
- float
List和Tuple
這就是Java或C中的數組.它是一個容器,能用來順序的,以整數索引方式檢索, 存儲一組對象.List用[]來表示,如[1, 2, 3]就是一個List;而Tuple用()來表示,如(3, 4, 5)就是一個Tuple.它們的區別在於List是可變的;而Tuple是不可變的.也就是說不可以增,刪和改.索引方式除了與Java一樣的以一個整數下標方式外,還可以指定開始,結束和步長,和使用負索引來分割List:
通用語法格式是:list[start:end:step]
- list[index] --- 返回第(index+1)個元素,受C語言影響,下標亦是從0開始
- list[start:end] --- 返回從start開始,到end-1,也就是list[start], list[start+1].....list[end-1]
- list[start:end:step] --- 與上面類似,只不過每隔step取一個
- list[:end] ---- 缺省的開端是0
- list[start:] ---- 缺省的結尾是len(list),或者-1
正數索引 0 1 2 3實例:
數組元素 [1] [3] [5] [7]
負數索引 -4 -3 -2 -1
List是一個對象,它有一此內置的方法,如:
- >>> a = [1, 3, 5, 7];
- >>> a[0]
- 1
- >>> a[3]
- 7
- >>> a[-1]
- 7
- >>> a[-2]
- 5
- >>> a[0:3]
- [1, 3, 5]
- >>> a[1:3:2]
- [3]
- >>> a[0:3:2]
- [1, 5]
- >>> a[0:-1:2]
- [1, 5]
- >>>
- 包含關係: in, not in
- >>> 3 in a
- True
- >>> 8 in a
- False
- >>> 8 not in a
- True
- >>>
- 連接符: +
- >>> a + [9, 11]
- [1, 3, 5, 7, 9, 11]
- 重複: *
- >>> a * 2
- [1, 3, 5, 7, 1, 3, 5, 7]
- >>>
字符串String
字符串就是一個字符的數組,List的操作都可以對String直接使用.
- >>> str = 'hello, world'
- >>> str[0:3]
- 'hel'
- >>> str[0:3:2]
- 'hl'
- >>> str[-1]
- 'd'
- >>> str * 2
- 'hello, worldhello, world'
- >>> '3' in str
- False
- >>> 'le' in str
- False
- >>> 'el' in str
- True
- >>> 'ell' not in str
- False
- >>>
字串格式化符%
這是一個類似C語言printf和Java中的String.format()的操作符,它能格式化字串,整數,浮點等類型:語句是:formats % (var1, var2,....)它返回的是一個String.
- >>> "Int %d, Float %d, String '%s'" % (5, 2.3, 'hello')
- "Int 5, Float 2, String 'hello'"
- >>>
Dictionary字典
相當於Java中的HashMap,用於以Key/Value方式存儲的容器.創建方式爲{key1: value1, key2: value2, ....}, 更改方式爲dict[key] = new_value;索引方式爲dict[key]. dict.keys()方法以List形式返回容器中所有的Key;dict.values()以List方式返回容器中的所有的Value:
- >>> box = {'fruits': ['apple','orange'], 'money': 1993, 'name': 'obama'}
- >>> box['fruits']
- ['apple', 'orange']
- >>> box['money']
- 1993
- >>> box['money'] = 29393
- >>> box['money']
- 29393
- >>> box['nation'] = 'USA'
- >>> box
- {'money': 29393, 'nation': 'USA', 'name': 'obama', 'fruits': ['apple', 'orange']}
- >>> box.keys()
- ['money', 'nation', 'name', 'fruits']
- >>> box.values()
- [29393, 'USA', 'obama', ['apple', 'orange']]
- >>>
分支語句
格式爲:其中邏輯表達式可以加上括號(),也可以不加.但如果表達式裏面比較混亂,還是要加上括號,以提高清晰.但整體的邏輯表達式是可以不加的:
- if expression:
- blocks;
- elif expression2:
- blocks;
- else:
- blocks;
- >>> a = 3; b = 4; c = 5;
- >>> if a == b and a != c:
- ... print "Are you sure"
- ... elif (a == c and b == c):
- ... print "All equal"
- ... else:
- ... print "I am not sure"
- ...
- I am not sure
- >>>
while循環
與Java中類似:while expression:
blocks
- >>> i = 0;
- >>> while i < 3:
- ... print "I am repeating";
- ... i += 1;
- ...
- I am repeating
- I am repeating
- I am repeating
- >>>
for語句
與Java中的foreach語法一樣, 遍歷List:for var in list:
blocks;
- >>> msg = "Hello";
- >>> for c in msg:
- ... print c;
- ...
- H
- e
- l
- l
- o
- >>>
數組推導
這是Python最強大,也是最性感的功能:list = [expression for var in list condition]它相當於這樣的邏輯:
list = [];一句話,相當於這麼多邏輯,可見數組推導是一個十分強大的功能:
for var in list:
if condition:
execute expression;
add result of expression to list
return list;
遍歷列表a,對其是偶數的項,乘方.
- >>> a = range(4);
- >>> a
- [0, 1, 2, 3]
- >>> [x*x for x in a if x % 2 == 0]
- [0, 4]
- >>>
函數
如何定義函數def function_name(args):調用函數的方式function_name(formal_args):
function_body;
Python中函數也是一個對象,可以賦值,可以拷貝,可以像普通變量那樣使用.其實可以理解爲C語言中的指針:
- >>> def power(x):
- ... return x*x;
- ...
- >>> power(4)
- 16
- >>>
另外就是匿名函數,或者叫做lambda函數,它沒有名字,只有參數和表達式:
- <pre name="code" class="python">>>> d = power;
- >>> d(2)
- 4</pre>
- <pre></pre>
lambda args: expression
lambda最大的用處是用作實參:
- >>> d = lambda x: x*x;
- >>> d(2)
- 4
- >>> def iter(func, list):
- ... ret = [];
- ... for var in list:
- ... ret.append(func(var));
- ... return ret;
- ...
- >>> iter(lambda x: x*x, a)
- [0, 1, 4, 9]
- >>>
一些常用的內置函數
所謂內置函數,就是不用任何導入,語言本身就支持的函數:- print --- 打印輸出
print var1, var2, var3
- >>> a
- [0, 1, 2, 3]
- >>> d
- <function <lambda> at 0x7f668c015140>
- >>> print a, d
- [0, 1, 2, 3] <function <lambda> at 0x7f668c015140>
- >>>
print與%結合更爲強大:
print formats % (var1, var2, ...):
- >>> print "today is %d, welcome %s" % (2013, 'alex');
- today is 2013, welcome alex
- >>>
其實這沒什麼神祕的,前面提到過%格式化返回是一個字串,所以print僅是輸出字串而已,格式化工作是由%來做的.
- len()---返回列表,字串的長度
- range([start], stop, [step]) --- 生成一個整數列表,從,start開始,到stop結束,以step爲步長
- >>> range(4)
- [0, 1, 2, 3]
- >>> range(1,4)
- [1, 2, 3]
- >>> range(1,4,2)
- [1, 3]
- >>>
- help(func)---獲取某個函數的幫助文檔.
執行系統命令行命令
import subprocess;- check_call(commands, shell=True)可以執行一個命令,並檢查結果:
- >>> check_call("ls -l .", shell=True);
- total 380
- -rw-r--r-- 1 alex alex 303137 Jun 28 23:25 00005.vcf
- drwxrwxr-x 3 alex alex 4096 Jun 28 23:57 3730996syntheticseismogram
- -rw-rw-r-- 1 alex alex 1127 Jun 28 23:45 contacts.txt
- -rw-rw-r-- 1 alex alex 3349 Jun 29 00:19 contacts_vcard.vcf
- drwxr-xr-x 2 alex alex 4096 Jun 15 18:43 Desktop
- drwxr-xr-x 3 alex alex 4096 Jun 22 08:59 Documents
- drwxr-xr-x 9 alex alex 4096 Jul 3 20:34 Downloads
- -rw-r--r-- 1 alex alex 8445 Jun 15 18:17 examples.desktop
- drwxrwxr-x 5 alex alex 4096 Jun 19 23:01 gitting
- -rw-rw-r-- 1 alex alex 0 Jun 19 20:21 libpeerconnection.log
- drwxr-xr-x 2 alex alex 4096 Jun 15 18:43 Music
- -rw-rw-r-- 1 alex alex 148 Jul 4 22:46 persons.txt
- drwxr-xr-x 3 alex alex 4096 Jul 4 23:08 Pictures
- drwxr-xr-x 2 alex alex 4096 Jun 15 18:43 Public
- -rw-rw-r-- 1 alex alex 65 Jul 8 22:15 py.py
- -rw-rw-r-- 1 alex alex 271 Jul 4 21:28 speech.txt
- -rw-rw-r-- 1 alex alex 93 Jul 3 23:02 speech.txt.bak
- drwxr-xr-x 2 alex alex 4096 Jun 15 18:43 Templates
- drwxrwxr-x 2 alex alex 4096 Jun 22 19:01 Ubuntu One
- drwxr-xr-x 2 alex alex 4096 Jun 15 18:43 Videos
- 0
- >>>
check_call是相當於在Shell上執行一個語句,所以可以發揮想像力,組合Shell命令:
- >>> check_call("ls -l . | grep 'py'", shell=True);
- -rw-rw-r-- 1 alex alex 65 Jul 8 22:15 py.py
- 0
- >>>
所以,這是相當強大的工具,可以像寫Shell腳本那樣,結合管道幹一些大事!
- check_output(cmds, shell=True)執行命令,並以字串形式返回結果:
- >>> a = check_output("ls -l .", shell=True);
- >>> a
- 'total 380\n-rw-r--r-- 1 alex alex 303137 Jun 28 23:25 00005.vcf\ndrwxrwxr-x 3 alex alex 4096 Jun 28 23:57 3730996syntheticseismogram\n-rw-rw-r-- 1 alex alex 1127 Jun 28 23:45 contacts.txt\n-rw-rw-r-- 1 alex alex 3349 Jun 29 00:19 contacts_vcard.vcf\ndrwxr-xr-x 2 alex alex 4096 Jun 15 18:43 Desktop\ndrwxr-xr-x 3 alex alex 4096 Jun 22 08:59 Documents\ndrwxr-xr-x 9 alex alex 4096 Jul 3 20:34 Downloads\n-rw-r--r-- 1 alex alex 8445 Jun 15 18:17 examples.desktop\ndrwxrwxr-x 5 alex alex 4096 Jun 19 23:01 gitting\n-rw-rw-r-- 1 alex alex 0 Jun 19 20:21 libpeerconnection.log\ndrwxr-xr-x 2 alex alex 4096 Jun 15 18:43 Music\n-rw-rw-r-- 1 alex alex 148 Jul 4 22:46 persons.txt\ndrwxr-xr-x 3 alex alex 4096 Jul 4 23:08 Pictures\ndrwxr-xr-x 2 alex alex 4096 Jun 15 18:43 Public\n-rw-rw-r-- 1 alex alex 65 Jul 8 22:15 py.py\n-rw-rw-r-- 1 alex alex 271 Jul 4 21:28 speech.txt\n-rw-rw-r-- 1 alex alex 93 Jul 3 23:02 speech.txt.bak\ndrwxr-xr-x 2 alex alex 4096 Jun 15 18:43 Templates\ndrwxrwxr-x 2 alex alex 4096 Jun 22 19:01 Ubuntu One\ndrwxr-xr-x 2 alex alex 4096 Jun 15 18:43 Videos\n'
- >>> b = check_output("ls -l . | grep 'py'", shell=True);
- >>> b
- '-rw-rw-r-- 1 alex alex 65 Jul 8 22:15 py.py\n'
- >>>
不用我說你就知道它的強大之處了!唯一需要注意的就是換行符也在裏面,處理的時候需要注意!
正則表達式
Python也是支持正則表達式的,至於正則表達式,跟其他的語言如Java,C沒什麼差別,這裏說說如何使用正則表達式來進行匹配:如:
- import re;
- p = re.compile(expression);
- m = p.search(target);
- if m != None:
- # got match
- else:
- # no match
這些就是Python的入門基礎知識, 瞭解了這些內容,我相信就可以使用Python來完成你的需要,比如寫一些小工具之類的.對於大部分的日常工作,或者一些小工具來說,這些東西就足夠了!
- >>> message = 'Welcome to the year of 2013';
- >>> import re;
- >>> p = re.compile('(\d+)');
- >>> m = p.search(message);
- >>> m
- <_sre.SRE_Match object at 0x7f668c015300>
- >>> print m.group(1)
- 2013
- >>>
但是如果想學會Python,或者想學好Python,這纔是一個小小的開端,最好讀一讀<Python核心編程>這本書,相當的不錯.
推薦資料:
- Learn Python the Hard Way這是一個相當好的網站.它的最大優點在於以實例爲核心來講解.缺點就是講的不是很深入,非常適合入門漢.
- <Core Python Programming>這本書相當的好,內容詳細,且有練習題可以做
- Coding Bat這上面有很多Python的練習題,很多都是關於String和List的,非常適合初學者練手
- Python for fun這上面有很多小型的項目.可以用來練習.