《笨辦法學Python》 第25課手記

2021-07-09 16:54:34 字數 2941 閱讀 4490

本節課內容較多,如果不理解可以先嘗試做正確,然後再來理解。我們的學習已經由最初的簡單向複雜轉變了,希望你能咬牙堅持下來,只要能沒有遺漏的學到最後,相信我們都能掌握好python。同時通過這麼長時間的學習,我理解了很多人喜歡python的原因。因為相較與c家族,python真的有一種簡潔的美感,而且易懂。

原**如下:

def

break_words

(stuff):

"""this function break up words for us."""

words = stuff.split(' ')

return words

defsort_words

(words):

"""sorts the words."""

return sorted(words)

defprint_first_word

(words):

"""prints the first word after popping it off."""

word = words.pop(0)

print word

defprint_last_word

(words):

"""prints the last word after popping it off."""

word = words.pop(-1)

print word

defsort_sentence

(sentence):

"""takes in a full sentence and returns the sorted words."""

words = break_words(sentence)

return sort_words(words)

defprint_first_and_last

(sentence):

"""prints the first and last words of the sentence."""

words = break_words(sentence)

print_first_word(words)

print_last_word(words)

defprint_first_and_last_sorted

(sentence):

"""sorted the words then prints the first and last one."""

words = sort_sentence(sentence)

print_first_word(words)

print_last_word(words)

這段**定義了7個函式,裡面用」「」括起來的英文解釋了每個函式的功能。

而且在命令列介面輸入help(函式名)可以調出」「」裡面的內容,因此可以看做是幫助文件。由此可以窺見預定義函式可能也是以該種形式定義的。

這段**涉及的新的用法:

def

sort_sentence

(sentence):

"""takes in a full sentence and returns the sorted words."""

words = break_words(sentence)

return sort_words(words)

在乙個函式的定義中呼叫了另乙個函式,注意呼叫的函式必須是先前定義的,即遵循先定義再呼叫的順序。這裡不同於c語言可以先寫乙個函式宣告,然後可以將函式定義寫到後面的做法。

這裡的7個函式實際上組成了乙個模組,這和我們過去使用sys模組類似,但sys是預先就定義好的,ex25這個模組,是我們自己手動定義的。是不是感覺很棒呢!你現在已經可以自己定義模組了呢!

結果如下:

(>>>是你手動輸入的內容,其他的是直譯器輸出的內容)

在這裡面有兩處與書中給出的結果不一樣的地方:

這是因為我將words打成了wrods而引起的錯誤,如果你是對的,則不會出現中的內容。

這裡的^d是在鍵盤上按下ctrl+d的意思,但這裡出錯是因為windows power shell環境下退出是ctrl+z,所以^z才是正確用法。當出現ps c:\users\你電腦的使用者名稱時,說明當前處於無任何操作狀態,在這裡表示成功退出。

以該種方式執行之後,ex25.py所在資料夾會自動生成乙個叫ex25.pyc的檔案

1.stuff.split(』 『),以空格為標誌分割字串,預設全部分割,可以在括號裡」後面指定引數以使直譯器按規定次數分割。

比如stuff.split(」,1)只分割一次,分割結果是』all』和』good things come to those who wait.』

2.sorted(words),以字母表順序為依據將words變數所包含的字串中的英文單詞進行排序,英文句號在該過程中將被捨棄。

3.word = words.pop(0),彈出乙個元素後關閉,括號內的引數表示彈出元素的位置。0代表第乙個,-1代表最後乙個。暫不清楚單位是不是之前類似的位元組,之前碰到位置引數時,數字代表的是第幾個位元組數。請記住這種用法,也記住這個疑問。稍後再碰到一些具體的例子就能理解了。

4.用法:先排序,在輸出第乙個或者最後乙個,是求最值的常用方法,sql語言中可以先將sc表中的grade降序排序,然後輸出第乙個求最高分。也請記住這種用法。

《笨辦法學Python》 第4課手記

這節課目的是讓你掌握變數,跟c語言非常類似,很簡單。左邊是變數名用 號給變數賦值。不同的是我沒有看到變數宣告,作者是直接賦值,拿過來就用的。至於接下來作者舉的報錯那個例子,如果你把變數名打錯的情況下就會出現,因為變數名一旦打錯,python將不能識別,也就無法在print中輸出對應的值。這裡我們可以...

《笨辦法學Python》 第6課手記

第6課講字串和文字,作者給出的 如下 x there are d types of people.10 binary binary do not don t y those who know s and those who s.binary,do not print xprint yprint i ...

《笨辦法學Python》 第8課手記

第八課沒有新內容,作者在常見問題解答裡面說得很清楚,建議每一課的常見問題解答都要仔細閱讀。如下 formatter r r r r print formatter 1,2,3,4 print formatter one two three four print formatter formatter...