L20 函数和文件
1.进一步学习文件读取,使用readline方法逐行读取,学习和使用seek控制指针指向文件中的指定位置(详见加分题seek备注。)
#coding:utf-8
#习题 20: 函数和文件
#用as可以更改import进来的方法名
from sys import argv as myarg
script, input_file = myarg
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 += 1
print_a_line(current_line, current_file)
current_line +=1
print_a_line(current_line, current_file)
"""
加分题:
1.通读脚本,在每行之前加上注解,以理解脚本里发生的事情。
2.每次 print_a_line 运行时,你都传递了一个叫 current_line 的变量。
在每次调用函数时,打印出 current_line 的值,跟踪一下它在 print_a_line 中是怎样变成 line_count 的。
"current_line"这个变量作为"print_a_line"的参数传递一个值给"print_a_line"方法,在这个方法中会把值赋给"line_count"变量,参与计算。
3.找出脚本中每一个用到函数的地方。检查 def 一行,确认参数没有用错。
4.上网研究一下 file 中的 seek 函数是做什么用的。试着运行 pydoc file 看看能不能学到更多。
#seek 函数是用来指定文件位置的函数,使用方法
#seek (offset[, whence])
#第一个值(offset)用来指定偏移的大小,可有正负。
#第二个值(whence)用来指定开始位置,'0'代表绝对开始位置(默认值),'1'代表当前指针所在位置,'2'代表绝对结束位置。
#例字符串[abcdefg],当读取到abcd时,使用seek(0),那么就能回到a之前,此时打印全部就能打印出[abcdefg]
#这时使用seek(0,1),就相当于当前位置,等于没变化。
#这是使用seek(2,1),就相当于从在当前位置往后三个位置,也就是从g开始,此时能够输出g。
#这时使用seek(-2,2),就像先回到最末尾,然后往前两个位置,此时能够输出[fg]。
5.研究一下 += 这个简写操作符的作用,写一个脚本,把这个操作符用在里边试一下。
递增符号。已直接优化进代码。
"""
L21 函数可以返回东西
1.返回值概念,这部分没有很大问题。
#coding:utf-8
#习题 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 "MUTIPLYING %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)
height = subtract(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, subtract(height, multiply(weight, divide(iq, 2))))
print "The becomes: ", what, "Can you do it by hand?"
"""
加分题:
1.如果你不是很确定 return 的功能,试着自己写几个函数出来,让它们返回一些值。你可以将任何可以放在 = 右边的东西作为一个函数的返回值。
2.这个脚本的结尾是一个迷题。我将一个函数的返回值用作了另外一个函数的参数。我将它们链接到了一起,就跟写数学等式一样。这样可能有些难读,不过运行一下你就知道结果了。接下来,你需要试试看能不能用正常的方法实现和这个表达式一样的功能。
3.一旦你解决了这个迷题,试着修改一下函数里的某些部分,然后看会有什么样的结果。你可以有目的地修改它,让它输出另外一个值。
4.最后,颠倒过来做一次。写一个简单的等式,使用一样的函数来计算它。
return概念理解没什么问题,用返回值作为参数也没什么理解问题。
"""