本文適用於Python 2.5.4版,參考文件http://www.python.org/doc/2.5.4/。
這篇Python教學手冊目標放在介紹Python的程式語法,內容以常用的語法為主,更進階的用法請參考官方網站說明,目的是提供學習者一些應該注意而且必須知道的知識。
先談談變數(variable),程式處理中一定會使用到變數,Python中的變數不需要宣告(declaration)就可以使用!再說明一次,Python中的變數不需要宣告就可以使用,所以Python用起來相當自由。另外,Python的變數名稱、模組名稱等其他名稱是區分大小寫(Case-Sensitive ),程式結尾不需要分號(semicolon)結束,謹記。
還有,注意到一般程式語言使用花括號的地方,Python中則不使用花括號包住敘述式,而是利用冒號(colon),對於剛學習Python的人必須習慣這個冒號的用法!像是迴圈、函式宣告、物件宣告的地方等等。
變數是讓你處理資料(data),資料則可依據類型區分,Python是具有高階的資料型態(data type),所以非常適合複雜的資料操作。Python中所有的資料都是物件(object),只是類型不同。Python內建的物件類型有:
三個關鍵字所定義:None, NotImplemented, Ellipsis
數值(Number):integer, long, float, complex, bool
序列(Sequence):str, unicode, basestring, list, tuple, xrange
映射(Mapping):dict
集合(Set):set, frozenset
這些物件中,注意到Python分成兩類:
mutable:可變的,宣告後,可以對變數的資料進行修改,即可讀可寫。如list, dict, set物件類型。
immutable:不可變的,宣告後,變數的資料不可以修改,即唯讀。如str, tuple, unicode, frozenset物件類型。
注意到沒有Array陣列的物件,其實物件的功能可以使用"Python內建的物件"取代,當然Python也提供array模組,如果你喜歡的話也可以使用array模組的功能。
註解(comment):Python使用井字號(number sign, pound sign, hash symbol)來達到單行註解,在Python中並未定義多行註解,但可使用三個引號(triple-quotes,也就是"""或’’’)宣告字串當作多行註解。
再來談談常用的資料物件:
數(Number):可以是整數或浮點數(有小數點就是浮點數),Python特別的是內建複數(Complex Number),僅需在虛數的部分加上j或J字尾。
字串(String):使用單引號(single quote)或雙引號(double quote)圍起的文字,可以在字串前面加入"r"表示原始字串(raw string),另外表示為Unicode字串則前面加入"u"。
清單list:使用「方括號(square brackets, closed brackets or box brackets)」宣告。list大概是Python中最常使用的資料類型。
值組tuple:使用「圓括號(round brackets, open brackets or parentheses)」宣告。
字典dict:使用「花括號(curly brackets, squiggly brackets, definite brackets, swirly brackets, birdie brackets or braces)」宣告。
認識Python中的資料後,程式處理少不了控制流程(Control Flow),分成兩部分說明:「決策」與「迴圈」,語法也和其他程式語言類似。
決策(condition)敘述總共有三個:if, else, elif,其中elif是「else if」的縮寫,注意到Python中沒有「switch...case」判斷敘述的使用,取而代之的是利用if和多個elif的方式達成多重判斷。
迴圈(loop)的敘述有:for和while兩個敘述語法。for迴圈一定搭配in使用,for迴圈不同於一般程式語言的使用方式,必須使用序列(sequence)的資料類型,也常常搭配range()函式,利用in語法遊走於序列中的元素(item)運算,詳細用法請參考官方網站的文件說明。while就簡單多了,如同一般程式語言的用法。另外,迴圈也可以利用break和continue終止或繼續執行迴圈。
內建函式與內建常數是位於Python之中的__builtin__模組。
__import__(name[, globals[, locals[, fromlist[, level ]]]])
abs(x)
all(iterable)
any(iterable)
basestring()
bool([x ])
callable(object)
chr(i)
classmethod(function)
cmp(x, y)
compile(string, filename, kind[, flags[, dont inherit ]])
complex([real[, imag ]])
delattr(object, name)
dict([arg ])
dir([object ])
divmod(a, b)
enumerate(iterable)
eval(expression[, globals[, locals ]])
execfile(filename[, globals[, locals ]])
file(filename[, mode[, bufsize ]])
filter(function, iterable)
float([x ])
frozenset([iterable ])
getattr(object, name[, default ])
globals()
hasattr(object, name)
hash(object)
help([object ])
hex(x)
id(object)
input([prompt ])
int([x[, radix ]])
isinstance(object, classinfo)
issubclass(class, classinfo)
iter(o[, sentinel ])
len(s)
list([iterable ])
locals()
long([x[, radix ]])
map(function, iterable, ...)
max(iterable[, args... ][key ])
min(iterable[, args... ][key ])
object()
oct(x)
open(filename[, mode[, bufsize ]])
ord(c)
pow(x, y[, z ])
property([fget[, fset[, fdel[, doc ]]]])
range([start, ] stop[, step ])
raw_input([prompt ])
reduce(function, iterable[, initializer ])
reload(module)
repr(object)
reversed(seq)
round(x[, n ])
set([iterable ])
setattr(object, name, value)
slice([start, ] stop[, step ])
sorted(iterable[, cmp[, key[, reverse ]]])
staticmethod(function)
str([object ])
sum(iterable[, start ])
super(type[, object-or-type ])
tuple([iterable ])
type(object)
type(name, bases, dict)
unichr(i)
unicode([object[, encoding [, errors ]]])
vars([object ])
xrange([start, ] stop[, step ])
zip([iterable, ... ])
False
True
None
NotImplemented
Ellipsis
__debug__
學習Python Language可以參閱官方網站,有兩個部分一定要閱讀。
The Python Language Reference
說明Python程式語言的宣告和語法。
The Python Standard Library
說明Python標準程式庫,使用Python幾乎都會使用的程式庫。