【Python爬蟲】-笨辦法學(xué) Python 習(xí)題18-26

一昧旨、作業(yè)內(nèi)容

笨辦法學(xué) Python 習(xí)題18-26以及加分題臼予。

二、作業(yè)代碼:

# 習(xí)題 18:命名窄锅、變量缰雇、代碼、函數(shù)
# 知識(shí)點(diǎn)總結(jié):
# 一疏之、函數(shù)可以給代碼片段命名暇咆,就跟變量和數(shù)字命名一樣
# 二爸业、它們可以接受參數(shù),就跟你的腳本接受argv一樣拯爽。
# 三钧忽、通過使用#1和#2耸黑,它們可以讓你創(chuàng)建微型腳本或者小命令。
#  this one is like your scripts with argv
# 用def定義函數(shù)print_two备禀,參數(shù)為*args
def print_two(*args):
    # 將args解包,將所有的參數(shù)依次賦予左邊的變量名
    arg1, arg2 = args
    # 打印包含格式化變量的字符串a(chǎn)rg1: %r, arg2: %r 赋续,變量名分別為arg1和arg2
    print("arg1: %r, arg2: %r" % (arg1, arg2))

# ok, that *args is actually pointless, we can just do this
# 用def定義函數(shù)print_two_again另患,參數(shù)分別為arg1和arg2
def print_two_again(arg1, arg2):
    # 打印包含格式化變量的字符串 arg1: %r, arg2: %r昆箕,變量名分別為arg1和arg2
    print("arg1: %r, arg2: %r" % (arg1, arg2))

# this just takes one argument
# 用def定義函數(shù)print_one,參數(shù)為arg1
def print_one(arg1):
    # 打印包含格式化變量的字符串 arg:1 %r薯嗤,變量名為arg1
    print("arg:1 %r" % arg1)

# this one takes no arguments
# 用def定義函數(shù)print_none
def print_none():
    # 打印字符串I got mothin.
    print("I got mothin.")

# 調(diào)用函數(shù)print_two()纤泵,參數(shù)為字符串Zed捏题,字符串Shaw
print_two("Zed", "Shaw")
# 調(diào)用函數(shù)print_two_again(),參數(shù)為字符串Zed带射,字符串Shaw
print_two_again("Zed", "Shaw")
# 調(diào)用函數(shù)print_one()循狰,參數(shù)為字符串First!
print_one("First!")
# 調(diào)用函數(shù)print_none()
print_none()

運(yùn)行結(jié)果如下:

"C:\Program Files\Python36\python.exe" E:/python3_project/ex18.py
arg1: 'Zed', arg2: 'Shaw'
arg1: 'Zed', arg2: 'Shaw'
arg:1 'First!'
I got mothin.

Process finished with exit code 0

加分習(xí)題
為自己寫一個(gè)函數(shù)注意事項(xiàng)以供后續(xù)參考绪钥。你可以寫在一個(gè)索引卡片上隨時(shí)閱讀,直到你記住所有的要點(diǎn)為止。注意事項(xiàng)如下:
1.函數(shù)定義是以 def 開始的嗎跪楞?
是侣灶。
2.函數(shù)名稱是以字符和下劃線 _ 組成的嗎褥影?
不一定。函數(shù)名稱可以是字符(不一定需要下劃線)校焦,能體現(xiàn)出函數(shù)的功能就夠了。
3.函數(shù)名稱是不是緊跟著括號 ( 氛雪?
是耸成。
4.括號里是否包含參數(shù)?多個(gè)參數(shù)是否以逗號隔開弦追?
是劲件。
5.參數(shù)名稱是否有重復(fù)左胞?(不能使用重復(fù)的參數(shù)名)
否。
6.緊跟著參數(shù)的是不是括號和冒號 ): 遍烦?
是服猪。
7.緊跟著函數(shù)定義的代碼是否使用了 4 個(gè)空格的縮進(jìn) (indent)拐云?
是。
8.函數(shù)結(jié)束的位置是否取消了縮進(jìn) (“dedent”)膳帕?
是危彩。

當(dāng)你運(yùn)行(或者說“使用 use”或者“調(diào)用 call”)一個(gè)函數(shù)時(shí)泳桦,記得檢查下面的要點(diǎn):
1.調(diào)運(yùn)函數(shù)時(shí)是否使用了函數(shù)的名稱?
2.函數(shù)名稱是否緊跟著 ( 谒府?
3.括號后有無參數(shù)完疫?多個(gè)參數(shù)是否以逗號隔開?
4.函數(shù)是否以 ) 結(jié)尾鸟顺?
# 習(xí)題19:函數(shù)和變量
# 創(chuàng)建名稱為cheese_and_crackers函數(shù),
# 參數(shù)分別為 cheese_count 和boxes_of_crackers
def cheese_and_crackers(cheese_count, boxes_of_crackers):
    # 打印包含格式化變量的字符串器虾,變量名為cheese_count
    print("You have %d cheeses!" % cheese_count)
    # 打印包含格式化變量的字符串兆沙,變量名為boxes_of_crackes
    print("You have %d boxes of crackers!" % boxes_of_crackers)
    # 打印字符串 Man that's enough for a party!
    print("Man that's enough for a party!")
    # 打印字符串 Get a blanket并換行
    print("Get a blanket.\n")

# 打印字符串 We can just give the function numbers directly:
# 調(diào)用函數(shù)cheese_and_crackers,變量名分別是20千扔,30
print("We can just give the function numbers directly:")
cheese_and_crackers(20, 30)

# 打印字符串
# 將整數(shù)10曲楚、50分別賦值給變量 amount_of_cheese和amount_of_crackers
print("OR, we can use variables from our script:")
amount_of_cheese = 10
amount_of_crackers = 50

# 調(diào)用函數(shù) cheese_and_crackers 變量名分別是amount_of_cheese, amount_of_crackers
cheese_and_crackers(amount_of_cheese, amount_of_crackers)

# 打印字符串 We can even do math inside too:
# 調(diào)用函數(shù)cheese_and_crackers褥符,變量名分別是整數(shù)10與20的和喷楣,整數(shù)5與6的和
print("We can even do math inside too:")
cheese_and_crackers(10 + 20, 5 + 6)

# 打印字符串 And we can combine the two, variables and math
# 調(diào)用函數(shù) cheese_and_crackers,
# 第一個(gè)變量名為變量amount_of_cheese 與整數(shù) 100的和
# 第一個(gè)變量名為amount_of_crackers 與整數(shù)1000的和
print("And we can combine the two, variables and math.")
cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000)

運(yùn)行結(jié)果如下:

"C:\Program Files\Python36\python.exe" E:/python3_project/ex19.py
We can just give the function numbers directly:
You have 20 cheeses!
You have 30 boxes of crackers!
Man that's enough for a party!
Get a blanket.

OR, we can use variables from our script:
You have 10 cheeses!
You have 50 boxes of crackers!
Man that's enough for a party!
Get a blanket.

We can even do math inside too:
You have 30 cheeses!
You have 11 boxes of crackers!
Man that's enough for a party!
Get a blanket.

And we can combine the two, variables and math.
You have 110 cheeses!
You have 1050 boxes of crackers!
Man that's enough for a party!
Get a blanket.


Process finished with exit code 0

加分習(xí)題
1.倒著將腳本讀完逊朽,在每一行上面添加一行注解叽讳,說明這行的作用坟募。
2.從最后一行開始婿屹,倒著閱讀每一行推溃,讀出所有的重要字符來。
3.自己編至少一個(gè)函數(shù)出來蜂奸,然后用10種方法運(yùn)行這個(gè)函數(shù)扩所。
# 習(xí)題 20: 函數(shù)和文件
# 通過from...inport...導(dǎo)入sys模組,將argv直接導(dǎo)入程序
from sys import argv
# 將argv解包助赞,將所有的參數(shù)依次賦予左邊的變量名
script, input_file = argv
# 用def定義函數(shù)print_all,參數(shù)為f
def print_all(f):
    # 在f上調(diào)用read()函數(shù)袁勺,無需任何參數(shù)期丰。讀取文本的內(nèi)容并打印出來
    print(f.read())
# 用def定義函數(shù)rewind,參數(shù)為f
def rewind(f):
    # 在f上調(diào)用seek()函數(shù)
    f.seek(0)
# 用def定義函數(shù)print_a_line()街立,參數(shù)分別為line_count和f
def print_a_line(line_count, f):
    # 打印變量line_count.
    # 在f上調(diào)用readline()函數(shù)赎离,無需任何參數(shù)植阴。讀取文本文件中的一行,并打印出來
    print(line_count, f.readline())
# open()函數(shù)用于打開文件憾朴,括號內(nèi)為輸入?yún)?shù)众雷,參數(shù)為文件名做祝,并存放到變量 current_file
current_file = open(input_file)
# 打印字符串 First let's print the whole file:\n
print("First let's print the whole file:\n")
# 調(diào)用函數(shù)print_all()混槐,參數(shù)為current_file
print_all(current_file)
# 打印字符串 Now let's rewind, kind of like a tape.
print("Now let's rewind, kind of like a tape.")
# 調(diào)用函數(shù) rewind(),參數(shù)為current_file
rewind(current_file)
# 打印字符串 Let's print three lines:
print("Let's print three lines:")
# 將整數(shù)1賦值給變量 current_line
current_line = 1
# 調(diào)用函數(shù) print_a_line()狠鸳,參數(shù)為current_line, current_file
print_a_line(current_line, current_file)
# 將變量 current_line 的值和整數(shù)1相加運(yùn)算件舵,并把結(jié)果存放到變量 current_line
current_line = current_line + 1
# 調(diào)用函數(shù)print_a_line(),參數(shù)為current_line, current_file
print_a_line(current_line, current_file)
# 將變量 current_line 的值和整數(shù)1相加運(yùn)算坑质,并把結(jié)果存放到變量 current_line
current_line = current_line + 1
# 調(diào)用函數(shù)print_a_line()临梗,參數(shù)為current_line, current_file
print_a_line(current_line, current_file)

命令行運(yùn)行結(jié)果如下:

E:\python3_project>python ex20.py filename.txt
First let's print the whole file:

To all the people out there.
I say I don't like my hair.
I need to share it off.

Now let's rewind, kind of like a tape.
Let's print three lines:
1 To all the people out there.

2 I say I don't like my hair.

3 I need to share it off.
加分習(xí)題
1.通讀腳本夜焦,在每行之前加上注解茫经,以理解腳本里發(fā)生的事情。
2.每次 print_a_line 運(yùn)行時(shí)抹镊,你都傳遞了一個(gè)叫 current_line 的變量荤傲。在每次調(diào)用函數(shù)時(shí)遂黍,打印出 current_line 的值,跟蹤一下它在 print_a_line 中是怎樣變成 line_count 的铃彰。
3.找出腳本中每一個(gè)用到函數(shù)的地方芯咧。檢查 def 一行敬飒,確認(rèn)參數(shù)沒有用錯(cuò)。
4.上網(wǎng)研究一下 file 中的 seek 函數(shù)是做什么用的带到。試著運(yùn)行 pydoc file 看看能不能學(xué)到更多揽惹。
5.研究一下 += 這個(gè)簡寫操作符的作用,寫一個(gè)腳本,把這個(gè)操作符用在里邊試一下箭养。
# 加分習(xí)題1.2.3.4.
# 通過from...inport...導(dǎo)入sys模組毕泌,將argv直接導(dǎo)入程序
from sys import argv
# 將argv解包,將所有的參數(shù)依次賦予左邊的變量名
script, input_file = argv
# 用def定義函數(shù)print_all,參數(shù)為f
def print_all(f):
    # 在f上調(diào)用read()函數(shù)挠说,無需任何參數(shù)损俭。讀取文本的內(nèi)容并打印出來
    print(f.read())
# 用def定義函數(shù)rewind潘酗,參數(shù)為f
def rewind(f):
    # 1.在f上調(diào)用fp.seek(offset, from_what)函數(shù)仔夺,fp是正在使用的文件指針,offset是移動(dòng)多少位置日裙,from_what定義參考點(diǎn)
    # 2.關(guān)于參考點(diǎn)惰蜜,0:表示參考點(diǎn)是文件的開頭 1:參考點(diǎn)是當(dāng)前的文件位置 2:表示參考點(diǎn)是文件的結(jié)尾
    # 3.如果省略蝎抽,from_what默認(rèn)為0
    f.seek(0)
# 用def定義函數(shù)print_a_line()樟结,參數(shù)分別為line_count和f
def print_a_line(line_count, f):
    # 打印變量line_count.
    # 在f上調(diào)用readline()函數(shù),無需任何參數(shù)碎连。讀取文本文件中的一行驮履,并打印出來
    print(line_count, f.readline())
# open()函數(shù)用于打開文件,括號內(nèi)為輸入?yún)?shù)怠噪,參數(shù)為文件名杜跷,并存放到變量 current_file
current_file = open(input_file)
# 打印字符串 First let's print the whole file:\n
print("First let's print the whole file:\n")
# 調(diào)用函數(shù)print_all()葛闷,參數(shù)為current_file
print_all(current_file)
# 打印字符串 Now let's rewind, kind of like a tape.
print("Now let's rewind, kind of like a tape.")
# 調(diào)用函數(shù) rewind(),參數(shù)為current_file
rewind(current_file)
# 打印字符串 Let's print three lines:
print("Let's print three lines:")
# 將整數(shù)1賦值給變量 current_line
current_line = 1
# 調(diào)用函數(shù) print_a_line()阳仔,參數(shù)為current_line, current_file
print_a_line(current_line, current_file)
# 將變量 current_line 的值和整數(shù)1相加運(yùn)算近范,并把結(jié)果存放到變量 current_line
current_line = current_line + 1
# 調(diào)用函數(shù)print_a_line()延蟹,參數(shù)為current_line, current_file
print_a_line(current_line, current_file)
# 將變量 current_line 的值和整數(shù)1相加運(yùn)算等孵,并把結(jié)果存放到變量 current_line
current_line = current_line + 1
# 調(diào)用函數(shù)print_a_line()俯萌,參數(shù)為current_line, current_file
print_a_line(current_line, current_file)
# 習(xí)題 21: 函數(shù)可以返回東西
def add(a, b):
    print("ADDING %d + %d" % (a, b))
    return a + b

def subtract(a, b):
    print("SUBTRACTING %d - %d" % (a, b))
    return a - b

def  multiply(a, b):
    print("MULTIPLYING %d * %d" % (a, b))
    return a * b

def divide(a, b):
    print("DIVIDING %d / %d" % (a, b))
    return a / b


print("Let's to some math with just funcitons!")

age = add(30, 5)
height = subtract(78, 4)
weight = multiply(90, 2)
iq = divide(100, 2)

print("Age: %d, Height: %d, Weight: %d, IQ: %(age, height, weight, iq")


# A puzzle for the extra creadit, type it in anyway.
print("Here is a puzzle.")

what = add(age, subtract(height, multiply(weight, divide(iq, 2))))

print("That  becomes: ", what, "Can you do it by hand?")

運(yùn)行結(jié)果如下:

"C:\Program Files\Python36\python.exe" E:/python3_project/ex21.py
Let's to some math with just funcitons!
ADDING 30 + 5
SUBTRACTING 78 - 4
MULTIPLYING 90 * 2
DIVIDING 100 / 2
Age: %d, Height: %d, Weight: %d, IQ: %(age, height, weight, iq
Here is a puzzle.
DIVIDING 50 / 2
MULTIPLYING 180 * 25
SUBTRACTING 74 - 4500
ADDING 35 + -4426
That  becomes:  -4391.0 Can you do it by hand?

Process finished with exit code 0
加分習(xí)題
1.如果你不是很確定 return 的功能咐熙,試著自己寫幾個(gè)函數(shù)出來,讓它們返回一些值返弹。你可以將任何可以放在 = 右邊的東西作為一個(gè)函數(shù)的返回值义起。
2.這個(gè)腳本的結(jié)尾是一個(gè)迷題。我將一個(gè)函數(shù)的返回值用作了另外一個(gè)函數(shù)的參數(shù)。我將它們鏈接到了一起偿凭,就跟寫數(shù)學(xué)等式一樣两疚。這樣可能有些難讀诱渤,不過運(yùn)行一下你就知道結(jié)果了谈况。接下來鸦做,你需要試試看能不能用正常的方法實(shí)現(xiàn)和這個(gè)表達(dá)式一樣的功能谓着。
3.一旦你解決了這個(gè)迷題赊锚,試著修改一下函數(shù)里的某些部分治筒,然后看會(huì)有什么樣的結(jié)果。你可以有目的地修改它舷蒲,讓它輸出另外一個(gè)值耸袜。
4.最后,顛倒過來做一次牲平。寫一個(gè)簡單的等式堤框,使用一樣的函數(shù)來計(jì)算它。

習(xí)題 22: 到現(xiàn)在你學(xué)到了哪些東西纵柿?
首先,回到你的每一個(gè)習(xí)題的腳本里昂儒,把你碰到的每一個(gè)詞和每一個(gè)符號(symbol沟使,character的別名)寫下來。確保你的符號列表是完整的渊跋。
符號列表

習(xí)題 23: 讀代碼
一邊一讀邊做《簡明 Python 教程》的練習(xí)腊嗡。

# 習(xí)題 24: 更多練習(xí)
print("Let's practice everything.")
print('You\'d need to know \'about escapes with \\ that do \n newlines and \t tabs.')

poem = """
\tThe lovely world
with logic so firmly planted
cannot discern \n the needs of love
nor comprehend passion from intuition
and requires an explanation
\n\t\twhere there is none.
"""

print("--------------")
print(poem)
print("--------------")


five = 10 - 2 + 3 - 6
print("This should be five: %s" % five)

def secret_formula(started):
    jelly_beans = started * 500
    jars = jelly_beans / 1000
    crates = jars / 100
    return jelly_beans, jars, crates


start_point = 10000
beans, jars, crates = secret_formula(start_point)

print("With a starting point of: %d" % start_point)
print("We'd have %d beans, %d jars, and %d crates." % (beans, jars, crates))

start_point = start_point / 10

print("We can also do that this way:")
print("We'd have %d beans, %d jars, and %d crates." % secret_formula(start_point))

運(yùn)行結(jié)果如下:

"C:\Program Files\Python36\python.exe" E:/python3_project/ex24.py
Let's practice everything.
You'd need to know 'about escapes with \ that do 
 newlines and    tabs.
--------------

    The lovely world
with logic so firmly planted
cannot discern 
 the needs of love
nor comprehend passion from intuition
and requires an explanation

        where there is none.

--------------
This should be five: 5
With a starting point of: 10000
We'd have 5000000 beans, 5000 jars, and 50 crates.
We can also do that this way:
We'd have 500000 beans, 500 jars, and 5 crates.

Process finished with exit code 0

加分習(xí)題
記得仔細(xì)檢查結(jié)果,從后往前倒著檢查拾酝,把代碼朗讀出來燕少,在不清楚的位置加上注釋。
故意把代碼改錯(cuò)蒿囤,運(yùn)行并檢查會(huì)發(fā)生什么樣的錯(cuò)誤棺亭,并且確認(rèn)你有能力改正這些錯(cuò)誤。
# 習(xí)題 25: 更多更多的練習(xí)
def break_words(stuff):
    """This function will break up words for us."""
    words = stuff.splif(' ')
    return words

def sort_words(words):
    """Sorts the words."""
    return sorted(words)

def print_first_word(words):
    """Prints the first word after popping if off."""
    word = words.pop(0)
    print(word)

def print_last_word(words):
    """Prints the Last word after popping it off."""
    word = words.pop(-1)
    print(word)

def sort_sentence(sentence):
    """Takes in full sentence and returns the sorted word."""
    words = break_words(sentence)
    return sort_words(words)

def print_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)

def print_first_and_last_sorted(sentence):
    """Sorts the words then prints the first and Last one."""
    words = sort_sentence(sentence)
    print_first_word(words)
    print_last_word(words)

命令行運(yùn)行結(jié)果報(bào)錯(cuò):

C:\Windows\system32>python
Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 18:41:36) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import ex25
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'ex25'

查了下Stack Overflow,有個(gè)哥們問了同樣的問題镶摘,一位熱心的答主解了惑:
因?yàn)槲业奈募窂讲辉谙到y(tǒng)路徑上嗽桩,因此Python不知道我的ex25模塊可以在哪里找到。
再一次于命令行中運(yùn)行凄敢,這一次出現(xiàn)了新的問題:

C:\Windows\system32>python
Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 18:41:36) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path.append(r'E:\python3_project')
>>> import ex25
>>> sentence = "All good things come to those who wait."
>>> words = ex25.break_words(sentence)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "E:\python3_project\ex25.py", line 7, in break_words
    words = stuff.splif(' ')
AttributeError: 'str' object has no attribute 'splif'

???♂?沒看清把split 打成了splif 碌冶。再來一次:

C:\Windows\system32>python
Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 18:41:36) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path.append(r'E:\python3_project')
>>> import ex25
>>> sentence = "All good things come to those who wait."
>>> words = ex25.break_words(sentence)
>>> words
['All', 'good', 'things', 'come', 'to', 'those', 'who', 'wait.']
>>> sort_words = ex25.sort_words(words)
>>> sort_words
['All', 'come', 'good', 'things', 'those', 'to', 'wait.', 'who']
>>> ex25.print_first_word(words)
All
>>> ex25.print_last_word(words)
wait.
>>> wrods
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'wrods' is not defined
>>> words
['good', 'things', 'come', 'to', 'those', 'who']
>>> ex25.print_first_word()
Traceback (most recent call last):
  File "", line 1, in 
TypeError: print_first_word() missing 1 required positional argument: 'words'
>>> ex25.print_first_word(sort_words)
All
>>> ex25.print_last_word(sort_words)
who
>>> sort_words
['come', 'good', 'things', 'those', 'to', 'wait.']
>>> sorted_words = ex25.sort_sentence(sentence)
>>> sorted_words
['All', 'come', 'good', 'things', 'those', 'to', 'wait.', 'who']
>>> ex25.print_first_and_last(sentence)
All
wait.
>>> ex25.print_first_and_last_sorted(sentence)
All
who
>>> 
加分習(xí)題
1.研究答案中沒有分析過的行,找出它們的來龍去脈涝缝。確認(rèn)自己明白了自己使用的是模組 ex25 中定義的函數(shù)扑庞。
2.試著執(zhí)行 help(ex25) 和 help(ex25.break_words) 。這是你得到模組幫助文檔的方式拒逮。 所謂幫助文檔就是你定義函數(shù)時(shí)放在 """ 之間的東西罐氨,它們也被稱作 documentation comments (文檔注解),后面你還會(huì)看到更多類似的東西滩援。
3.重復(fù)鍵入 ex25. 是很煩的一件事情栅隐。有一個(gè)捷徑就是用 from ex25 import * 的方式導(dǎo)入模組。這相當(dāng)于說:“我要把 ex25 中所有的東西 import 進(jìn)來玩徊∽馇模”程序員喜歡說這樣的倒裝句,開一個(gè)新的會(huì)話恩袱,看看你所有的函數(shù)是不是已經(jīng)在那里了泣棋。
4.把你腳本里的內(nèi)容逐行通過 python 編譯器執(zhí)行,看看會(huì)是什么樣子畔塔。你可以執(zhí)行CTRL-D (Windows 下是 CTRL-Z)來關(guān)閉編譯器潭辈。
# 加分習(xí)題1.
# 此練習(xí)需要在命令行中先輸入以下內(nèi)容:
# >>>import sys
# >>>sys.path.append(r'E:\python3_project')
# >>>import ex25

# 用def定義函數(shù) break_words,參數(shù)為stuff
# 在stuff上調(diào)用split()函數(shù)澈吨,參數(shù)為 ' '萎胰,并存放到變量words
# 返回變量words的值
def break_words(stuff):
    """This function will break up words for us."""
    words = stuff.split(' ')
    return words

# 用def定義函數(shù) sort_words(),參數(shù)為words
# 調(diào)用sorted()函數(shù)對參數(shù)進(jìn)行排序棚辽,并將值返回
def sort_words(words):
    """Sorts the words."""
    return sorted(words)

# 用def定義函數(shù) print_first_word()技竟,參數(shù)為words
# 在words上調(diào)用pop() 函數(shù)用于移除列表中的一個(gè)元素(默認(rèn)最后一個(gè)元素),參數(shù)為0(第一個(gè)元素)屈藐。并且返回該元素的值榔组。并存放到變量word
# 打印變量word
def print_first_word(words):
    """Prints the first word after popping if off."""
    word = words.pop(0)
    print(word)

# 用def定義函數(shù) print_last_word,參數(shù)為words
# 在words上調(diào)用pop() 函數(shù)用于移除列表中的一個(gè)元素(默認(rèn)最后一個(gè)元素)联逻,參數(shù)為-1(最后一個(gè)元素)搓扯。并且返回該元素的值。并存放到變量word
# 打印變量word
def print_last_word(words):
    """Prints the Last word after popping it off."""
    word = words.pop(-1)
    print(word)

# 用def定義函數(shù) sort_sentence包归,參數(shù)為 sentence
# 調(diào)用函數(shù) sort_sentence锨推,參數(shù)為 sentence,并將結(jié)果存放到變量 words
# 調(diào)用函數(shù) sort_words,參數(shù)為 words换可,并將結(jié)果返回
def sort_sentence(sentence):
    """Takes in full sentence and returns the sorted word."""
    words = break_words(sentence)
    return sort_words(words)

# 用def定義函數(shù) print_first_and_last椎椰,參數(shù)為 sentence
# 調(diào)用函數(shù) break_words,參數(shù)為sentence沾鳄,并將結(jié)果存放到變量 words
# 調(diào)用函數(shù) print_first_word慨飘,參數(shù)為 words
# 調(diào)用函數(shù) print_last_word,參數(shù)為 words
def print_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)

# 用def定義函數(shù) print_first_and_last_sorted译荞,參數(shù)為 sentence
# 調(diào)用函數(shù) sort_sentence瓤的,參數(shù)為sentence,并將結(jié)果存放到變量 words
# 調(diào)用函數(shù) print_first_word吞歼,參數(shù)為 words
# 調(diào)用函數(shù) print_last_word圈膏,參數(shù)為 words
def print_first_and_last_sorted(sentence):
    """Sorts the words then prints the first and Last one."""
    words = sort_sentence(sentence)
    print_first_word(words)
    print_last_word(words)
# 習(xí)題 26: 恭喜你,現(xiàn)在可以考試了篙骡!


def break_words(stuff):
    """This function will break up words for us."""
    words = stuff.split(' ')
    return words

def sort_words(words):
    """Sorts the words."""
    return sorted(words)

def print_first_word(words):
    """Prints the first word after popping it off."""
    word = words.pop(0)
    print(word)

def print_last_word(words):
    """Prints the last word after popping it off."""
    word = words.pop(-1)
    print(word)

def sort_sentence(sentence):
    """Takes in a full sentence and returns the sorted words."""
    words = break_words(sentence)
    return sort_words(words)

def print_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)

def print_first_and_last_sorted(sentence):
    """Sorts the words then prints the first and last one."""
    words = sort_sentence(sentence)
    print_first_word(words)
    print_last_word(words)


print("Let's practice everything.")
print('You\'d need to know\'bout escapes with\\that do\nnewlines and\ttabs.')

poem = """
\tThe lovely world
with logic so firmly planted
cannot discern \n the needs of love
nor comprehend passion from intuition
and requires an explantion
\n\t\twhere there is none.
"""


print("--------------")
print(poem)
print("--------------")

five = 10 - 2 + 3 - 5
print("This should be five: %s" % five)

def secret_formula(started):
    jelly_beans = started * 500
    jars = jelly_beans / 1000
    crates = jars / 100
    return jelly_beans, jars, crates


start_point = 10000
beans, jars, crates = secret_formula(start_point)

print("With a starting point of: %d" % start_point)
print("We'd have %d jeans, %d jars, and %d crates." % (beans, jars, crates))

start_point = start_point / 10

print("We can also do that this way:")
print("We'd have %d beans, %d jars, and %d crabapples." % secret_formula(start_point))


sentence = "All god\tthings come to those who weight."

words = break_words(sentence)
sorted_words = sort_words(words)

print_first_word(words)
print_last_word(words)
print_first_word(sorted_words)
print_last_word(sorted_words)
sorted_words = sort_sentence(sentence)
print(sorted_words)

print_first_and_last(sentence)

print_first_and_last_sorted(sentence)

這個(gè)練習(xí)的目的不是寫程序稽坤,而是修正現(xiàn)有的程序……

三、學(xué)習(xí)總結(jié)

  • 練習(xí)的過程中医增,遇到的很多問題已在作業(yè)內(nèi)容(注釋)中解釋清楚。
  • 實(shí)在不理解可以上 Stack Overflow 尋找?guī)椭铣妫贿^新手遇到的絕大多數(shù)問題都可以找到問題和答案參考叶骨。
  • 這周的作業(yè)有一半是在 Pythonista 3 上完成的,通勤時(shí)無聊打開做做練習(xí)什么的祈匙,這個(gè)應(yīng)用非常強(qiáng)大忽刽,也非常好用!
    下面是一些細(xì)節(jié)的補(bǔ)充夺欲,主要是做習(xí)題的過程中難以理解的部分:
    習(xí)題 21 里出現(xiàn)了return這個(gè)概念跪帝。可以看看這個(gè)知乎問題些阅,很容易理解伞剑。

習(xí)題 25 中的pop()函數(shù)和sorted()函數(shù),下面的相關(guān)練習(xí)市埋,幫助理解:

pop()函數(shù)
classmates = ['bob', 'about', 'Zoo', 'Credit']
print(classmates)

# 要?jiǎng)h除list末尾的元素黎泣,用pop()方法:
classmates.pop()
print(classmates)

# 刪除指定位置的元素,用pop(i)方法缤谎,i是索引位置:
classmates.pop(1)
print(classmates)
# 排序算法
# 使用 Python 內(nèi)置函數(shù) sorted()就可以對list進(jìn)行排序
print(sorted([36, 5, -12, 9, -21]))

# 接受一個(gè) key 函數(shù)來實(shí)現(xiàn)自定義的排序抒倚,例如按絕對值大小排序:
print(sorted([36, 5, -12, 9, -21], key=abs))

# 默認(rèn)情況下,對字符串排序坷澡,是按照ASCII的大小比較的托呕,由于'Z' < 'a',結(jié)果大寫字母Z會(huì)排在小寫字母a的前面
print(sorted(['bob', 'about', 'Zoo', 'Credit']))

# 用key函數(shù)把字符串映射為忽略大小寫排序即可,忽略大小寫來比較兩個(gè)字符串项郊,實(shí)際上就是先把字富川都變成大寫(或者都變成小寫)馅扣,再比較。
print(sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower))

# 反向排序呆抑,不必改動(dòng)key函數(shù)岂嗓,可以傳入第三個(gè)參數(shù)reverse=True
print(sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True))
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市鹊碍,隨后出現(xiàn)的幾起案子厌殉,更是在濱河造成了極大的恐慌,老刑警劉巖侈咕,帶你破解...
    沈念sama閱讀 222,590評論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件公罕,死亡現(xiàn)場離奇詭異,居然都是意外死亡耀销,警方通過查閱死者的電腦和手機(jī)楼眷,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,157評論 3 399
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來熊尉,“玉大人罐柳,你說我怎么就攤上這事≌。” “怎么了张吉?”我有些...
    開封第一講書人閱讀 169,301評論 0 362
  • 文/不壞的土叔 我叫張陵,是天一觀的道長催植。 經(jīng)常有香客問我肮蛹,道長,這世上最難降的妖魔是什么创南? 我笑而不...
    開封第一講書人閱讀 60,078評論 1 300
  • 正文 為了忘掉前任伦忠,我火速辦了婚禮,結(jié)果婚禮上稿辙,老公的妹妹穿的比我還像新娘昆码。我一直安慰自己,他們只是感情好邻储,可當(dāng)我...
    茶點(diǎn)故事閱讀 69,082評論 6 398
  • 文/花漫 我一把揭開白布未桥。 她就那樣靜靜地躺著,像睡著了一般芥备。 火紅的嫁衣襯著肌膚如雪冬耿。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,682評論 1 312
  • 那天萌壳,我揣著相機(jī)與錄音亦镶,去河邊找鬼日月。 笑死,一個(gè)胖子當(dāng)著我的面吹牛缤骨,可吹牛的內(nèi)容都是我干的爱咬。 我是一名探鬼主播,決...
    沈念sama閱讀 41,155評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼绊起,長吁一口氣:“原來是場噩夢啊……” “哼精拟!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起虱歪,我...
    開封第一講書人閱讀 40,098評論 0 277
  • 序言:老撾萬榮一對情侶失蹤蜂绎,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后笋鄙,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體师枣,經(jīng)...
    沈念sama閱讀 46,638評論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,701評論 3 342
  • 正文 我和宋清朗相戀三年萧落,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了践美。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,852評論 1 353
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡找岖,死狀恐怖陨倡,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情许布,我是刑警寧澤兴革,帶...
    沈念sama閱讀 36,520評論 5 351
  • 正文 年R本政府宣布,位于F島的核電站爹脾,受9級特大地震影響帖旨,放射性物質(zhì)發(fā)生泄漏箕昭。R本人自食惡果不足惜灵妨,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,181評論 3 335
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望落竹。 院中可真熱鬧泌霍,春花似錦、人聲如沸述召。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,674評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽积暖。三九已至藤为,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間夺刑,已是汗流浹背缅疟。 一陣腳步聲響...
    開封第一講書人閱讀 33,788評論 1 274
  • 我被黑心中介騙來泰國打工分别, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人存淫。 一個(gè)月前我還...
    沈念sama閱讀 49,279評論 3 379
  • 正文 我出身青樓耘斩,卻偏偏與公主長得像,于是被迫代替她去往敵國和親桅咆。 傳聞我的和親對象是個(gè)殘疾皇子括授,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,851評論 2 361

推薦閱讀更多精彩內(nèi)容