從第二章開始吧!
1、程序輸出
a、使用print語句輸出:調(diào)用str(),將數(shù)值轉(zhuǎn)化成字符串
b、在交互式解釋器中輸出:調(diào)用repr()函數(shù),將一個對象轉(zhuǎn)化成字符串顯示,只是顯示用。
str()函數(shù)只是把字符串輸出而已,但是repr()則說明了輸出的是字符串。
str()與repr()具體差異會在第四章中提到。
>>> myString = 'hello world!'
>>> print myString
hello world!
>>> myString
'hello world!'
>>> str('hello world!')
'hello world!'
>>> repr('hello world!')
"'hello world!'"
2、程序輸入和raw_input()內(nèi)建函數(shù)
a、下劃線(_)表示:最后一個表達(dá)式的值
>>> myString = 'Hello World!'
>>> print myString
Hello World!
>>> myString
'Hello World!'
>>> _
'Hello World!'
b、Python的print語句與字符串格式運算符%結(jié)合使用,可實現(xiàn)字符串替換功能
>>> print "%s is number %d" %("python",1)
python is number 1
c、input()和raw_input()函數(shù)
input():希望能夠讀取一個合法的python表達(dá)式,如輸入字符串是必須使用引號將它廓起來。
raw_input():把所有輸入都當(dāng)作字符串處理。輸出的type為字符串。
>>> a = input('please enter:')
please enter:6
>>> print type(a)
<type 'int'>
>>> b = raw_input('please enter:')
please enter:6
>>> print type(b)
<type 'str'>
3、注釋
從#開始,直到一行結(jié)束的內(nèi)容都是注釋
>>> #one comment
... print 'hello world' #another comment
hello world
名為文檔字符串的特別注釋:可以在模塊、類或者函數(shù)的起始添加一個字符串,起到在線文檔的功能。與普通文檔不同,文檔字符串可以在運行時
訪問,也可以用來自動生成文檔。
def foo():
"This is a doc string."
return True
4、運算符
+ ? - ?* ?/ ?// ?% ?**
‘/’表示傳統(tǒng)除法,即如果兩個操作數(shù)都是整數(shù)的話,它將執(zhí)行地板除(取比商小的最大整數(shù))。
‘//’表示浮點除法(對結(jié)果進(jìn)行四舍五入)
優(yōu)先級:乘方(**) > 單目運算符-+ > * / // % >加減+-
< ?<= ?> ?>= ? == != ?<>(棄用)
>>> 2 < 4
True
>>> 2 ==4
False
>>> 2 > 4
False
>>> 6.2 < 6
False
>>> 6,2 <= 6.2
(6, True)
>>> 6.2 <= 6
False
>>> 6.2 <= 6.2000
True
>>> 6.2 < 6.2
False
and ?or ?not
>>> 2 < 4 and 2 == 4
False
>>> 2 > 4 or 2 < 4
True
>>> not 6.2 <=6
True
>>> 3 < 4 < 5
True
上面3 <4 <5是下面的縮寫
>>> 3 < 4 and 4 < 5
True
需要合理的使用括號增強(qiáng)代碼可讀性。
5、變量和賦值
變量名:字母、下劃線開頭。其余的字符可以是數(shù)字、字母或下劃線。
Python對大小寫敏感。
Python是動態(tài)類型語言,不需要預(yù)先聲明變量的類型,變量的類型和值在賦值那一刻被初始化,變量賦值使用等號執(zhí)行。
python支持:n *= 10,但是不支持C語言中的自增和自減運算符,Python會將--n解釋為-(-n),從而得到n,同樣++n的結(jié)果也是n,因為+-也是
表示正負(fù)的單目運算符。
6、數(shù)字
Python支持五種基本數(shù)字類型:
int: ? ?有符號整數(shù)
long: ? 長整數(shù),不要與C語言長整數(shù)混淆,python的長整型僅受限于用戶計算機(jī)虛擬內(nèi)存總數(shù)。
未來版本中,int和long將會無縫結(jié)合,長整數(shù)后綴"L"也變得可有可無。
bool: ? 布爾值,將布爾值用到一個數(shù)值上下文環(huán)境中(如將True與一個數(shù)字相加),True會被當(dāng)成數(shù)值1,而False會被當(dāng)成整數(shù)值0.
float: ?浮點值
complex:復(fù)數(shù)
在導(dǎo)入decimal模塊后,可以使用decimal數(shù)值類型,用于十進(jìn)制浮點數(shù)。
由于在二進(jìn)制表示中有一個無限循環(huán)片段,數(shù)字1.1無法用二進(jìn)制浮點數(shù)精確表示,數(shù)字1.1實際上會被表示成:
>>> 1.1
1.1000000000000001
>>> import decimal
>>> print decimal.Decimal('1.1')
1.1
7、字符串
Python中字符串被定義為引號之間的字符集合,支持成對的單引號或雙引號,三引號(三個連續(xù)的單引號或者雙引號)可用來包含特殊字符。
支持使用索引運算符([])和切片運算符([:])可以得到子字符串,字符串有其特有的索引規(guī)則:第一個字符的索引是0,最后一個字符的索引是-1.
加號(+)用于字符串連接,星號(*)用于字符串重復(fù)。
>>> pystr = '''python
... is cool'''
>>> pystr
'python\nis cool'
>>> print pystr
python
is cool
8、列表和元組
同一列表和元組能保存任意數(shù)量任意類型的Python對象,以0開始索引
列表:[],元素個數(shù)及元素的值可以改變
元組:(),不可更改
使用切片運算[]和[:]可以得到子集。
>>> aList = [1,2,3,4]
>>> aList
[1, 2, 3, 4]
>>> aList[0]
1
>>> aList[2:]
[3, 4]
>>> aList[:3]
[1, 2, 3]
>>> aList[1] = 5
>>> aList
[1, 5, 3, 4]
元組中數(shù)值不可改變:
>>> aTuple = ('robots',77,93,'try')
>>> aTuple
('robots', 77, 93, 'try')
>>> aTuple[:3]
('robots', 77, 93)
>>> aTuple[1] = 5
Traceback (most recent call last):
File "", line 1, in ?
TypeError: object does not support item assignment
9、字典
字典由鍵-值(key-value)對構(gòu)成,幾乎所有類型的Python對象都可以用作鍵,不過一般還是以數(shù)字或者字符串最為常用。
值可以是任意類型的Python對象,字典元素用大括號({})包裹
>>> aDict = {'host':'earth'}#create dict
>>> aDict['port'] = 80 # add to dict
>>> aDict
{'host': 'earth', 'port': 80}
>>> aDict.keys()
['host', 'port']
>>> aDict['host']
'earth'
>>> for key in aDict:
... ? print key,aDict[key]
...
host earth
port 80
10、代碼塊及縮進(jìn)對齊
代碼塊使用縮進(jìn)對齊來表達(dá)代碼邏輯,而不是使用大括號。
11、if語句
if ? ?expression1:
if_suite
elif ?expression2:
elif_suite
else:
else_suite
python中條件表達(dá)式并不需要加括號。
12、while循環(huán)
while ? ?expression:
while_suite
>>> counter = 0
>>> while counter < 3:
... ? print 'loop #%d' %(counter)
... ? counter += 1
...
loop #0
loop #1
loop #2
13、for循環(huán)和range()內(nèi)建函數(shù)
Python里面的for循環(huán)更像shell里面的foreach。Python中的for接受可迭代對象(例如序列或迭代器)作為其參數(shù),每次迭代其中一個元素:
>>> print 'I like to use the Internet for:'
I like to use the Internet for:
>>> for item in ['e-mail','net-surfing','homework','chat']:
... ? ? print item
...
net-surfing
homework
chat
print語句默認(rèn)給每一行添加一個換行符,只要在print語句的最后添加一個逗號(,)就可以改變這種行為,而且加逗號的print語句會在輸出的元素之間會自動添加一個空格:
>>> print 'I like to use the Internet for:'
I like to use the Internet for:
>>> for item in ['e-mail','net-surfing','homework','chat']:
... ? ? print item,
...
e-mail net-surfing homework chat
>>> who = 'knights'
>>> what = 'Ni!'
>>> print 'We are the',who,'who say',what,what,what,what
We are the knights who say Ni! Ni! Ni! Ni!
>>> print 'We are the %s who say %s'% \
... (who,((what + ' ')*4))
We are the knights who say Ni! Ni! Ni! Ni!
要達(dá)到遞增數(shù)值的效果:
>>> for eachNum in [0,1,2]:
... ? ?print eachNum,
...
0 1 2
因為我們要使用的數(shù)值范圍經(jīng)常變化,python提供了range()內(nèi)建函數(shù)來生成這種列表
>>> for eachNum in range(3):
... ? print eachNum
...
0
1
2
對字符串來說,很容易迭代每一個字符:
>>> for c in foo:
... ? print c,
...
a b c
range()經(jīng)常和len()一起用于字符串索引,下面顯示的是每一個元素及其索引值:
>>> foo = 'abc'
>>> for i in range(len(foo)):
... ? print foo[i],'(%d)'%i
...
a (0)
b (1)
c (2)
上述循環(huán)存在約束:要么循環(huán)索引,要么循環(huán)元素,這導(dǎo)致了enumerate()函數(shù)推出,它同時做到了這兩點:
>>> for i, ch in enumerate(foo):
... ? print ch, '(%d)'%i
...
a (0)
b (1)
c (2)
14、列表解析
可以在一行中使用一個for循環(huán)將所有值放到一個列表當(dāng)中
>>> sqdEvents = [x ** 2 for x in range(8) if not x %2]
>>>
>>> for i in sqdEvents:
... ? print i
...
0
4
16
36
15、文件和內(nèi)建函數(shù)open()、file
如何打開文件:
handle = open(file_name, access_mode = 'r')
file_name 變量包含我們希望打開的文件的字符串名字, access_mode 中 'r' 表示讀取,
'w' 表示寫入, 'a' 表示添加。其它可能用到的標(biāo)聲還有 '+' 表示讀寫, 'b'表示二進(jìn)制訪
問. 如果未提供 access_mode , 默認(rèn)值為 'r'。如果 open() 成功, 一個文件對象句柄會被
返回。所有后續(xù)的文件操作都必須通過此文件句柄進(jìn)行。當(dāng)一個文件對象返回之后, 我們就可
以訪問它的一些方法, 比如 readlines() 和close().文件對象的方法屬性也必須通過句點屬
性標(biāo)識法訪問。
訪問屬性的方法:句點屬性標(biāo)識法,即在對象名和屬性名之間加一個句點:object.attribute
filename = raw_input('Enter file name: ')
fobj = open(filename, 'r')
for eachLine in fobj:
print eachLine,
fobj.close()
對于print eachLine,后面帶逗號,是為了抑制出現(xiàn)\n,因為每行已經(jīng)有自帶的換行符了,不抑制\n會出現(xiàn)額外的空行。
此外,這是將文件內(nèi)容一次性讀出,然后再逐行顯示。
16、錯誤和異常
編譯時會檢查語法錯誤,Python也允許在程序運行時檢測錯誤。當(dāng)檢測到一個錯誤,Python解釋器就引發(fā)一個異常,并顯示異常的詳細(xì)信息。
要給你的代碼添加錯誤檢測及異常處理,只要將它們封裝在try-except語句中。try之后的代碼組是你打算管理的代碼。except之后的代碼組,則是你處理錯誤
的代碼。
>>> try:
... ? filename = raw_input('Enter file name: ')
... ? fobj = open(filename,'r')
... ? for eachLine in fobj:
... ? ? print eachline,fobj.close()
... except IOError,e:
... ? print 'file open error:',e
...
Enter file name: test
file open error: [Errno 2] No such file or directory: 'test'
程序員也可以用raise語句故意引發(fā)一個異常。
17、函數(shù)
函數(shù)在調(diào)用前必須先定義。如果函數(shù)中沒有return語句,則會自動返回None對象。Python是通過引用調(diào)用的,這意味著函數(shù)內(nèi)對參數(shù)的改變會影響到原始對象。
不過事實上只有可變對象會受此影響,對不可變對象來說,它的行為類似按值調(diào)用。
def function_name([arguments]):
"optional documentation string"
function_suite
參數(shù)中[]表示參數(shù)可選,調(diào)用python函數(shù)時不能省略()。
‘+’對于數(shù)字是兩數(shù)之和,對于字符串則是兩個字符串連接,對應(yīng)列表,則是:
>>> [1,2] + [3,4]
[1, 2, 3, 4]
函數(shù)的參數(shù)可以有一個默認(rèn)值,如果提供有默認(rèn)值:在函數(shù)定義中,參數(shù)以賦值語句定義。在提供默認(rèn)值的情況下,如果函數(shù)調(diào)用時沒提供這個參數(shù),就取這個值
作為默認(rèn)值。
>>> def foo(debug=True):
... ? 'determine if in debug mode with default argument'
... ? if debug:
... ? ? ?print 'in debug mode'
... ? print 'done'
...
>>> foo()
in debug mode
done
>>> foo(False)
done
18、類
定義類:
class ClassName(base_class[es]):
"optional documentation string"
static_member_declarations
method_declaration
使用class關(guān)鍵字定義類,可以提供一個可選的基類,如果沒有合適的基類,那就使用object作為基類。
>>> class FooClass(object):
... ? ?"""my very first class: FooClass"""
... ? ?version = 0.1 # class (data) attribute
... ? ?def __init__(self, nm='John Doe'):
... ? ? ? ?"""constructor"""
... ? ? ? ?self.name = nm # class instance (data) attribute
... ? ? ? ?print 'Created a class instance for', nm
... ? ?def showname(self):
... ? ? ? ?"""display instance attribute and class name"""
... ? ? ? ?print 'Your name is', self.name
... ? ? ? ?print 'My name is', self.__class__.__name__
... ? ?def showver(self):
... ? ? ? ?"""display class(static) attribute"""
... ? ? ? ?print self.version #references FooClass.version
... ? ?def addMe2Me(self,x): #does not use 'self'
... ? ? ? ?"""apply + operation to argument"""
... ? ? ? ?return x + x
...
上面定義的version是一個靜態(tài)變量,它將被所有實例及四個方法共享。
__init__()方法有一個特殊的名字,所有名字開始和結(jié)束都有兩個下劃線的方法都是特殊方法。當(dāng)一個類實例被創(chuàng)建時,__init__()會自動執(zhí)行,在類實例創(chuàng)建完畢
后執(zhí)行,__init__()可以被當(dāng)成構(gòu)建函數(shù),但是它并不創(chuàng)建實例----它僅僅是你的對象創(chuàng)建后執(zhí)行的第一個方法,它的目的是執(zhí)行一些該對象的必要的初始化工作。
通過創(chuàng)建自己的__init__()方法,可以覆蓋默認(rèn)的__init__()方法(默認(rèn)的方法什么也不做)。
在該例子中,初始化了一個名為name的類實例屬性,這個變量僅在類實例中存在,它并不是實際類本身的一部分。__init__()需要一個默認(rèn)的參數(shù)。
self是類實例自身的引用,類似其他語言的this
創(chuàng)建類實例
>>> foo1 = FooClass()
Created a class instance for John Doe
>>> foo1.showname()
Your name is John Doe
My name is FooClass
>>>
>>> foo1.showver()
0.1
>>> print foo1.addMe2Me(5)
10
>>> print foo1.addMe2Me('xyz')
xyzxyz
對于一個實例來說,self.__class__.__name__表示實例化它的類的名字,self.__class__引用實際的類。
上例沒有提供參數(shù),使用的是默認(rèn)參數(shù)'John Doe',下例是提供了參數(shù):
>>> foo2 = FooClass('Jane Smith')
Created a class instance for Jane Smith
>>> foo2.showname()
Your name is Jane Smith
My name is FooClass
19、模塊
模塊是一種組織形式,它將彼此有關(guān)系的Python代碼組織到一個個獨立文件當(dāng)中。模塊可以包含可執(zhí)行代碼,函數(shù)和類或者這些東西的組合。
當(dāng)你創(chuàng)建了一個python源文件,模塊的名字就是不帶.py后綴的文件名,一個模塊創(chuàng)建后,可從另一個模塊中使用import語句導(dǎo)入這個模塊來使用:
import module_name
訪問一個模塊函數(shù)或訪問一個模塊變量:
一旦導(dǎo)入完成,可用句點屬性標(biāo)識法訪問:
module.function()
module.variable
使用示例:
>>> import sys
>>> sys.stdout.write('Hello World!\n')
Hello World!
>>> sys.platform
'linux2'
>>> sys.version
'2.4.3 (#1, May ?5 2011, 16:39:10) \n[GCC 4.1.2 20080704 (Red Hat 4.1.2-50)]'
里面的write()不會自動在字符串后面添加換行符號,所以需要顯示添加'\n'
20、實用函數(shù)
內(nèi)建函數(shù): ? ? ? ? ? ? ? ? ? ? ? ? ? 描述
dir([obj]) ? ? ? ? ? ? ? ? ? ? ? ? ? 顯示對象的屬性,如果沒有提供參數(shù), 則顯示全局變量的名字
help([obj]) ? ? ? ? ? ? ? ? ? ? ? ? ?以一種整齊美觀的形式 顯示對象的文檔字符串, 如果沒有提供任何參
數(shù), 則會進(jìn)入交互式幫助。
int(obj) ? ? ? ? ? ? ? ? ? ? ? ? ? ? 將一個對象轉(zhuǎn)換為整數(shù)
len(obj) ? ? ? ? ? ? ? ? ? ? ? ? ? ? 返回對象的長度
open(fn, mode) ? ? ? ? ? ? ? ? ? ? ? 以 mode('r' = 讀, 'w'= 寫)方式打開一個文件名為 fn 的文件
range([[start,]stop[,step]) ? ? ? ? ?返回一個整數(shù)列表。起始值為 start, 結(jié)束值為 stop - 1; start
默認(rèn)值為 0, step默認(rèn)值為1。
raw_input(str) ? ? ? ? ? ? ? ? ? ? ? 等待用戶輸入一個字符串, 可以提供一個可選的參數(shù) str 用作提示信
息。
str(obj) ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? 將一個對象轉(zhuǎn)換為字符串
type(obj) ? ? ? ? ? ? ? ? ? ? ? ? ? ?返回對象的類型(返回值本身是一個type 對象?。?/p>