習題36、設計和調試
If 語句的規則
- 每一個
if 語句
必須包含一個else
. - 如果這個
else
永遠都不應該被執行到,因爲它本身沒有任何意義,那你必須在 else 語句後面使用一個叫做die
的函數,讓它打印出錯誤信息並且死給你看,這和上一節的習題類似,這樣你可以找到很多的錯誤。 if 語句
的嵌套不要超過 2 層,最好儘量保持只有 1 層。 這意味着如果你在 if 裏邊又有了一個if
,那你就需要把第二個 if 移到另一個函數裏面。- 將
if 語句
當做段落來對待,其中的每一個if
,elif
,else
組合就跟一個段落的句子組合一樣。在這種組合的最前面和最後面留一個空行以作區分。 - 你的布爾測試應該很簡單,如果它們很複雜的話,你需要將它們的運算事先放到一個變量裏,並
且爲變量取一個好名字。
循環的規則
- 只有在循環永不停止時使用
while 循環
,這意味着你可能永遠都用不到。這條只有 Python中成立,其他的語言另當別論。 - 其他類型的循環都使用
for 循環
,尤其是在循環的對象數量固定或者有限的情況下。
調試(debug)的小技巧
- 不要使用
debugger
。Debugger
所作的相當於對病人的全身掃描。你並不會得到某方面的有用信息,而且你會發現它輸出的信息態度,而且大部分沒有用,或者只會讓你更困惑。 - 最好的調試程序的方法是使用
print
在各個你想要檢查的關鍵環節將關鍵變量打印出來,從而檢查哪裏是否有錯。 - 讓程序一部分一部分地運行起來。不要等一個很長的腳本寫完後纔去運行它。寫一點,運行一點,再修改一點。
習題37、複習各種符號
Keywords(關鍵字)
- and
- del
- from
- not
- while
- as
- elif
- global
- or
- with
- assert
- else
- if
- pass
- yield
- break
- except
- import
- class
- exec
- in
- raise
- continue
- finally
- is
- return
- def
- for
- lambda
- try
數據類型
- True
- False
- None
- strings
- numbers
- floats
- lists
字符串轉義序列(Escape Sequences)
- \
- \’
- \”
- \a
- \b
- \f
- \n
- \r
- \t
- \v
字符串格式化(String Formats)
- %d
- %i
- %o
- %u
- %x
- %X
- %e
- %E
- %f
- %F
- %g
- %G
- %c
- %r
- %s
- %%
操作符
習題38、列表的操作
#!/usr/bin/python
# -*- coding:utf-8 -*-
states = {
'Oregon': 'OR',
'Florida': 'FL',
'California': 'CA',
'New York': 'NY',
'Michigan': 'MI'
}
cities = {
'CA': 'San Francisco',
'MI': 'Detorit',
'FL': 'Jacksonville'
}
cities['NY'] = 'New York'
cities['OR'] = 'Protland'
print '-' * 10
print "NY State has: ", cities['NY']
print "OR State has: ", cities['OR']
print '-' * 10
print "Michigan's abreviation is: ", states['Michigan']
print "Florida's abbreviation is: ", states['Florida']
print '-' * 10
for state, abbrev in states.items():
print "%s has the city %s" % (state, abbrev)
print '-' * 10
for state, abbrev in states.items():
print "%s state is abbreviated %s and has city %s" % (
state, abbrev, cities[abbrev])
print '-' * 10
state = states.get('Texas', None)
if not state:
print "Sorry, no Texas."
city = cities.get('TX', 'Does Not Exist')
print "The city for the state 'TX' is: %s" % city
小結
- 你不是說別用
while-loop
嗎?
是的。你要記住,有時候如果你有很好的理由,那麼規則也是可以打破的。死守着規則不放的人是白癡。stuff[3:5]
實現了什麼功能?
這是一個列表切片動作,它會從 stuff 列表的第 3 個元素開始取值,直到第 5 個元素。注意,這裏並不包含第 5 個元素,這跟range(3,5)
的情況是一樣的。- 爲什麼
join(' ', stuff)
不靈?
join 的文檔寫得有問題。其實它不是這麼工作的,其實它是你要插入的字符串的一個方法函數,函數的參數是你要連接的字符串構成的數組,所以應該寫作' '.join(stuff)
。
習題39、字典,可愛的字典
字典 可以將一個物件和另外一個東西關聯,不管它們的類型是什麼。
#!/usr/bin/python
# -*- coding:utf-8 -*-
class Song(object):
def __init__(self, lyrics):
self.lyrics = lyrics
def sing_me_a_song(self):
for line in self.lyrics:
print line
happy_bady = Song(["Happey birthday to you",
"I don't want to get sued",
"So I'll stop right there"])
bulls_on_parade = Song(["They rally around the family",
"With pockets full of shells"])
happy_bady.sing_me_a_song()
bulls_on_parade.sing_me_a_song()
小結
- 列表和字典有何不同?
列表是有序排列的一些物件,而字典是將一些物件(keys)對應到另外一些物件(values)的數據結構。- 字典能用在哪裏?
各種你需要通過某個值去查看另一個值的場合。其實你可以把字典當做一個“查詢表”。- 列表能用在哪裏?
列表是專供有序排列的數據使用的。你只要知道索引就能查到對應的值了。- 有沒有辦法弄一個可以排序的字典?
看看 Python 裏的collections.OrderedDict
數據結構。上網搜索一下文檔和用法。
習題40、模塊,類,對象
對於字典來說,key
是一個字符串,獲得值的語法是[key]
。對於模塊來說,key是函數或者變量的名稱,而語法是.key
。除了這個,它們基本上就沒什麼區別了。
#!/usr/bin/python
# -*- coding:utf-8 -*-
class Song(object):
def __init__(self, lyrics):
self.lyrics = lyrics
def sing_me_a_song(self):
for line in self.lyrics:
print line
happy_bady = Song(["Happey birthday to you",
"I don't want to get sued",
"So I'll stop right there"])
bulls_on_parade = Song(["They rally around the family",
"With pockets full of shells"])
happy_bady.sing_me_a_song()
bulls_on_parade.sing_me_a_song()
小結
- 爲什麼創建
_init__
或者別的類函數時需要多加一個 self 變量?
如果你不加self
,cheese = 'Frank'
這樣的代碼意義就不明確了,它指的既可能是實例的 cheese 屬性,或者一個叫做cheese
的局部變量。有了self.cheese ='Frank'
你就清楚地知道了這指的是實例的屬性self.cheese
。