习题 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:阅读一些代码
使用目前学到的知识,看自己能不能读懂一些代码,看出它们的功能来。