相關代碼詳見github地址:https://github.com/BMDACMER/Learn-Python
接着前天的總結
習題21:函數可以返回某些東西
定義函數的加減乘除,以及嵌套使用
習題22:回顧以前學的知識
習題23:字符串、字節串和字符編碼
綜合運用字符串、函數、文件讀取等知識。詳情如下:
from sys import argv script, encoding, error = argv # 命令行參數處理 def main(language_file, encoding,errors): line = language_file.readline() # 就是用readline()處理文本 if line: # 防止函數永遠循環下去 print_line(line, encoding, errors) return main(language_file, encoding, errors) def print_line(line, encoding, errors): # 對languages.txt中的每一行進行編碼 next_lang = line.strip() # 移除字符串頭尾指定的字符(默認為空格或換行符)或字符序列 raw_bytes = next_lang.encode(encoding,errors = errors) cooked_string = raw_bytes.decode(encoding, errors = errors) print(raw_bytes, "<===>",cooked_string) languages = open("language.txt",encoding = "utf-8") main(languages, encoding, error)
習題24: 更多的練習
部分代碼如下:
start_point = start_point / 10 print("We can also do that this way:") formula = secret_formula(start_point) # this is an easy way to apply a list to a format string print("we'd have {} beans,{} jars, and {} crates.".format(*formula))
習題25:定義函數
習題26:回顧以前知識
習題27:
這一節 就是講解邏輯關系 邏輯術語的 and or not != == >= <= True False 以及真值表詳見P83
習題28:布爾表達式(跟C語言類似)
習題29:if語句
習題30: else 和 if 嵌套
# else if people = 30 cars = 40 trucks = 15 if cars > people: print("we should take the cars.") elif cars < people: print("We should not take the cars.") else: print("We can't decide.") if trucks > cars: print("That's too many trucks.") elif trucks < cars: print("Maybe we could take the trucks.") else: print("We still can't decide.") if people > trucks: print("Alright,let's just take the trucks.") else: print("Fine,let's stay home then.")
習題31:采用if-else語句編寫問答式“小游戲”
練習使用嵌套判斷語句
習題32:循環和列表
習題33:while循環
習題34:訪問列表的元素
習題35:綜合小練習,鞏固前面所學知識
習題36:設計和調試
注:debug最佳方式就是 使用print在各個想要檢查的關鍵點將變量打印出來,從而檢查哪里是否有錯!
習題37:復習各種符號
關鍵字 | 描述 | 示例 |
and | 邏輯與 | True and False == False |
as | with-as 語句的某一部分 | with X as Y: pass |
assert | 斷言(確保)某東西為真 | assert False, "Error!" |
break | 立即停止循環 | while True: break |
class | 定義類 | class Person(object) |
continue | 停止當前循環的后續步驟,再做一次循環 | while True: continue |
def | 定義函數 | def X(): pass |
del | 從字典中刪除 | del X[Y] |
elif | else if條件 | if: X; elif: Y; else: J |
else | else條件 | if: X; elif: Y; else: J |
except | 如果發生異常,運行此處代碼 | except ValueError, e: print(e) |
exec | 將字符串作為Python腳本運行 | exec 'print("hello")' |
finally | 不管是否發生異常,都運行此處代碼 | finally: pass |
for | 針對物件集合執行循環 | for X in Y: pass |
from | 從模塊中導入特定部分 | from X import Y |
global | 聲明全局變量 | global X |
if | if 條件 | if: X; elif: Y; /else: J |
import | 將模塊導入當前文件以供使用 | import os |
in | for循環的一步分,也可以是否在Y中的條件判斷 | for X in Y: pass 以及 1 in [1] == True |
is | 類似於==,判斷是否一樣 | 1 is 1 == True |
lambda | 船艦短匿名函數 | s = lambda y: y ** y; s(3) |
not | 邏輯非 | not True == False |
or | 邏輯或 | True or False == True |
pass | 表示空代碼塊 | def empty(): pass |
打印字符串 | print('this string') | |
raise | 出錯后引發異常 | raise ValueError("No") |
return | 返回值並推出函數 | def X(): return Y |
try | 嘗試執行代碼,出錯后轉到except | try: pass |
while | while循環 | while X: pass |
with | 將表達式作為一個變量,然后執行代碼塊 | with X as Y: pass |
yield | 暫停函數返回到調用函數的代碼中 | def X(): yield Y; X().next() |
數據類型 和 字符串轉義序列 等詳見P110--113
習題38:列表的操作
習題39:字典
小結:1)字典和列表有何不同?
答:列表是一些項的有序排列,而字典是將一些項(鍵)對應到另外一些項(值)的數據結構。
2)字典能用在哪里?
答:各章需要通過某個值取查看另一個值的場合。只要知道索引就能查到對應的值了。
3)有沒有辦法弄一個可以排序的字典?
答:看看python里的collections.OrderedDict數據結構。上網搜一下其文檔和用法。
習題40: 模塊、類和對象
question:為什么創建__init__或者別的類函數時需要多加一個self變量?
answer:如果不加self, cheese = 'Frank'這樣的代碼就有歧義了。它指的既可能使實例的cheese屬性,也可能是一個叫cheese的局部變量。有了self.cheese = 'Frank'就清楚地知道這指的是實例的屬性self.cheese.
習題41:學習面向對象術語
截取部分代碼(在線讀取文本信息)
import random from urllib.request import urlopen import sys WORD_URL = "http://learncodethehardway.org/words.txt" WORDS = [] # load up the words from the website for word in urlopen(WORD_URL).readlines(): WORDS.append(str(word.strip(),encoding="utf-8"))
習題42:對象、類及從屬關系
question1:對象和類的區別?
answer1: 對象和類好比 小狗和動物。對象是類的實例,也就是種特例。 書本例舉的 魚和泥鰍的關系。”is-a“和"has-a"的關系,”is-a“指的是魚和泥鰍的關系,而”has-a“指的是泥鰍和鰓的關系。
注:一般定義類時,在類名后面沒加(object),那么就默認添加(object)
習題43:編寫命令行的小游戲!
習題44:繼承和組合
- 隱式繼承
class Parent(object): def implicit(self): print("PARENT implicit()") class Child(Parent): pass dad = Parent() son = Child() dad.implicit() son.implicit()
輸出如下所示:PARENT implicit()
PARENT implicit() - 顯示覆蓋
class Parent(object): def override(self): print("PARENT override()") class Child(Parent): def override(self): print("CHILD override()") dad = Parent() son = Child() dad.override() son.override()
-
class Parent(object): def altered(self): print("PARENT altered()") class Child(Parent): def altered(self): print("CHILD, BEFORE PARENT altered()") super(Child, self).altered() # 采用super調用父類中的方法 print("CHILD, AFTER PARENT altered()") dad = Parent() son = Child() dad.altered() print("-----------------------------") son.altered()
- python支持多繼承 要用super()
class SuperFun(Child, BadStuff): pass