【Python爬蟲】-【第二周】02-作業

  1. 習題18 命名、變量、代碼、函數
# this one is like your scripts with argv
def print_two(*args):
      arg1, arg2 = args # 將參數解包,args意味著參數不固定 根據傳遞的參數去判斷參數
      print("arg1: %r, arg2: %r" % (arg1, arg2)) # 打印解包后的參數
# ok, that *args is actually pointless, we can just do this
def print_two_again(arg1, arg2): # 傳遞兩個參數,def print_two(*args): +   arg1, arg2 = args 作用一樣,合并了指定參數和參數解包的過程
      print("arg1: %r, arg2: %r" % (arg1, arg2))
# this just takes one argument
def print_one(arg1): # 定義一個函數,只接受一個變量并打印
      print("arg1: %r" % arg1)
# this one takes no arguments
def print_none(): # 定義一個函數,不接受變量傳遞,值打印一段文本。
      print("I got nothin.")
print_two("Zed", "Shaw")
print_two_again("Zed", "Shaw")
print_one("First!")
print_none()

加分習題:
函數定義注意事項:
1.函數定義以def開始;
2.函數名稱以字符和下劃線_組成(小寫字符,一般默認大寫字符為類);
3.函數名稱緊接著括號,括號里包含需要傳遞實參的形參名及形參個數;
4.括號里參數可以為空,也可以多個參數,參數之間用逗號隔開;
5.參數名稱不能重復;
6.緊接著參數的是右括號和冒號):
7.緊跟著函數定義的代碼使用了4個空格的縮進,表示這段代碼包含在函數定義代碼塊中;

8.函數結束的位置/下一個代碼段的開始,取消縮進。
函數調用注意事項:
1.使用函數名稱調用函數;
2.函數名稱后緊跟著括號;
3.根據函數定義,傳遞與定義中個數相符、順序相符的實參,多個參數之間以逗號隔開;
4.函數調用以)結果表示傳遞參數結束;
5.被調用函數的名稱需與被定義的函數名稱完全一致。

  1. 習題19 函數和變量
# 定義一個函數cheese_and_crackers,包含兩個參數,cheese_count和boxes_of_crackers。這個函數執行4個打印的任務。
def cheese_and_crackers(cheese_count, boxes_of_carckers):
      print("You have %d cheeses!" % cheese_count)
      print("You have %d boxes of crackers!" % boxes_of_carckers)
      print("Man that's enough for a party!")
      print("Get a blanket.\n")
print("We can just give the function numbers directly:")
cheese_and_crackers(20, 30) # 調用函數cheese_and_crackers函數,傳遞兩個參數,cheese_count = 20, boxes_of_crackers = 30
# 另外一種方式給函數傳遞參數
print("Or, we cam use variables from our script:")
amount_of_cheese = 10
amount_of_crackers = 50
cheese_and_crackers(amount_of_cheese, amount_of_crackers)
print("We can even do math inside too:")
cheese_and_crackers(10 + 20, 5 + 6) # 在函數中做運算,運算的結果為最終傳遞給函數的實參
print("And we can combine the two, variables and math:")
cheese_and_crackers(amount_of_crackers + 100, amount_of_crackers + 1000) # 在函數中做運算

加分習題:
19.2 自己編至少一個函數出來,

# 指定一個數,輸出從1到這個數(包含這個數)之間的所有數字
def f(n):
      current_number = 1
      while current_number <= n:
          print(current_number)
          current_number += 1
f(6) # 輸出結果為 1 2 3 4 5 6
  1. 習題20 函數和文件
from sys import argv # 從sys模塊調用argv函數
script, input_file = argv # 解包argv,需要傳遞腳本名稱script和input_file的名稱
# 讀取f文件內容并打印
def print_all(f):
    print(f.read())
# 移動文件讀取指針到文件開頭
def rewind(f):
    f.seek(0) # seek() 方法用于移動文件讀取指針到指定位置。
# 每次讀一行,并計數
def print_a_line(line_count, f):
    print(line_count, f.readline()) # readline() 方法用于從文件讀取整行,包括 "\n" 字符。如果指定了一個非負數的參數,則返回指定大小的字節數,包括 "\n" 字
current_file = open(input_file) # 打開文件,并將對象存儲于current_file變量
print("Frist let's print the whole file:\n")
print_all(current_file) # 打印輸出文件所有內容
print("Now let's rewind, kind of like a tape.")
rewind(current_file) # 移動文件讀取指針到文件開頭,從頭讀取文件
print("Let's print three lines:")
# 讀取文件第一行,并計數,輸出行號與行內容
current_line = 1
print_a_line(current_line, current_file)
# 讀取文件第二行,并計數,輸出行號與行內容
current_line = current_line + 1 # 等同于current_line += 1
print_a_line(current_line, current_file)
#  讀取文件第三行,并計數,輸出行號與行內容
current_line = current_line + 1
print_a_line(current_line, current_file)

學習筆記:關于readline()函數的行讀取方式

備注:readline()每運行一次,讀取一行,print_a_line運行三次就會依次打印1,2,3行,而不是打印第一行三次。
current_line = 1
print_a_line(current_line, current_file) # 打印第一行
print_a_line(current_line, current_file) # 打印第二行
print_a_line(current_line, current_file) # 打印第三行
  1. 習題21 函數可以返回東西
def add(a, b): # 定義一個函數,這個函數有兩個任務,打印一段文字,并將參數的和返回給函數
      print("ADDING %d + %d" % (a, b))
      return a + b
def substract(a, b):
      print("SUBSTRACTING %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 do some math with just functions!")
age = add(30, 5) # print(age) 輸出值35.但是age = add(30,5)的結果為print("ADDING %d + %d" % (a, b))。
height = substract(78, 4)
weight = multiply(90, 2)
iq = divide(100, 2)
print("Age: %d, Height: %d, Weight: %d, IQ: %d" % (age, height, weight, iq))
# A puzzle for the extra credit, type it in anyway.
print("Here is a puzzle.")
what = add(age, substract(height, multiply(weight, divide(iq, 2))))
print("That becomes: ", what, "Can you do it by hand?")
  1. 習題24 更多練習
print("Let's practice everything.")
print('You\'d need to know \'bout escapes with \\ that do \nnewlines and \t tabs.') # 轉義字符,正確打印
poem = """
\tThe lovely world
with logic so firmly planted
cannot discern \n the needs of lovely
nor comprehend passion from intuition
and requires an explanation
\n\t\twhere there is none.
""" # \t換行符,\n縮進,''''''輸出多行內容
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))
  1. 習題25 更多更多練習
import ex25 as p # 將文件夾中的ex25.py導入到此程序中,且命名為p
sentence = "All good things come to those who wait."
words = p.break_words(sentence) # 句點法調用ex25中的函數
print(words)
sorted_words = p.sort_words(words)
print(sorted_words)
p.print_first_word(words)
p.print_last_word(words)
# print(wrods) # name 'wrods' is not defined
print(words)
p.print_first_word(sorted_words)
p.print_last_word(sorted_words)
print(sorted_words)
sorted_words = p.sort_sentence(sentence)
print(sorted_words)
p.print_first_and_last(sentence)
p.print_first_and_last_sorted(sentence)

學習筆記:關注模組和函數的導入
《笨辦法學Pyhton》中是在先運行ex25.py,然后再python編譯器里進行的交互練習。
我的代碼里是在ex25.py的同一個目錄下新建了一個py文件,然后
import ex25 as p將ex25導入到程序中,再使用句點法調用ex25.py中定義的函數。

  1. 習題26 考試(改錯)
import ex25
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 \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 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 good things come to those who wait."
words = ex25.break_words(sentence)
sorted_words = ex25.sort_words(words)
print_first_word(words)
print_last_word(words)
ex25.print_first_word(sorted_words)
print_last_word(sorted_words)
sorted_words = ex25.sort_sentence(sentence)
print(sorted_words)
print_first_and_last(sentence)
print_first_and_last(sentence)

學習筆記:
**
代碼常見語法錯誤
①函數定義def f()后缺少:
②print要講打印的內容放在()內;
③除號是/而不是\;
④縮進錯誤;
與-的輸入錯誤,另外函數名及參數名都只能是字母與數字以及的組合,并且不能以數字開頭;
⑥使用了未定義的參數名、變量名;
⑦調用模組或模組中的函數需在代碼前幾行先導入;
⑧函數名、變量名輸入錯誤。
**


心得體會:
新手學習python最容易犯的代碼錯誤有兩種,分別是語法錯誤邏輯錯誤
語法錯誤是指代碼違背了代碼語言的語法,例如括號不匹配、變量名稱書寫錯誤、使用了未定義的變量名等等,導致編譯器進行語法檢查時不通過。
邏輯錯誤是程序能運行,但是達不到預期結果。
語法錯誤很容易犯,很多細微的差別都可能使編譯器報錯。除了寫代碼時要細心之外,我們還要學會通過編譯器的錯誤代碼,發現錯誤并快速定位、改寫語法錯誤的代碼。

Paste_Image.png
Paste_Image.png

Pycharm、Sublime Txt等工具都自帶語法高亮、錯誤提示,善用這些工具能夠極大提高我們的效率,減少語法錯誤。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容