《 笨方法學 Python 》_ 習題 18
阿新 • • 發佈:2019-02-17
習題 18:命名、變數、程式碼和函式
# this one is like your scripts with argv def print_two(*args): arg1, arg2 = args print("arg1: %r, arg2: %r" % (arg1, arg2)) # ok, that *argv is actually pointless, we can just do this def print_two_again(arg1, arg2): 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 nothing.") print_two("Zed", "Shaw") print_two_again("Zed", "Shaw") print_one("First!") print_none()
*args 裡的 * 的功能是告訴 Python 把函式的所有引數都接收進來,然後放到名叫 args 的列表中去,一般不經常用到這個東西。
習題 19:函式和變數
函式裡的變數和腳本里的變數之間是沒有聯絡的,可以直接給函式傳遞數字,也可以給它變數,還可以給它數學表示式,甚至可以把數學表示式是和變數合起來用。
def cheese_and_crackers(cheese_count, boxes_of_crackers): print("You hace %d cheese!" % cheese_count) print("You hace %d boxes pf crackers!" % boxes_of_crackers) 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) print("OR, we can 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_cheese + 100, amount_of_crackers + 1000)
習題 20:函式和檔案
from sys import argv script, input_file = argv def print_all(f): print(f.read()) def rewind(f): f.seek(0) def print_a_line(line_count, f): print(line_count, f.readline()) current_file = open(input_file) print("First 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 print_a_line(current_line, current_file) current_line = current_line + 1 print_a_line(current_line, current_file)
seek() 函式用於移動檔案讀取指標到指定位置,file.seek(0) 回到了檔案的開始。
readline() 函式會掃描檔案的每一個位元組,直到找到一個 \n 位置,然後它停止讀取檔案,並且返回此前的檔案內容。file.readline() 檔案 file 會記錄每次呼叫 readline() 後的讀取位置,這樣它就可以在下次被呼叫時讀取接下來的一行了。
習題 21:函式可以返回某些東西
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 do some math with just function!")
age = add(20, 5)
height = subtract(180, 2)
weight = multiply(90, 2)
iq = divide(200, 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, subtract(height, multiply(weight, divide(iq, 2))))
print("That becomes:", what, "Can you do it by hand?")
習題 22:到現在你學到了哪些東西
回顧一下到現在為止已經學到的所有知識。
習題 23:閱讀一些程式碼
使用目前學到的知識,看自己能不能讀懂一些程式碼,看出它們的功能來。