欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

習題 20: 函數(shù)和文件?

回憶一下函數(shù)的要點,然后一邊做這節(jié)練習,一邊注意一下函數(shù)和文件是如何在一起協(xié)作發(fā)揮作用的。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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)

特別注意一下,每次運行 print_a_line 時,我們是怎樣傳遞當前的行號信息的。

你應(yīng)該看到的結(jié)果?

$ python ex20.py test.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 shave 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 shave it off.

$

加分習題?

  1. 通讀腳本,在每行之前加上注解,以理解腳本里發(fā)生的事情。
  2. 每次 print_a_line 運行時,你都傳遞了一個叫 current_line 的變量。在每次調(diào)用函數(shù)時,打印出 current_line 的至,跟蹤一下它在 print_a_line 中是怎樣變成 line_count 的。
  3. 找出腳本中每一個用到函數(shù)的地方。檢查 def 一行,確認參數(shù)沒有用錯。
  4. 上網(wǎng)研究一下 file 中的 seek 函數(shù)是做什么用的。試著運行 pydoc file 看看能不能學到更多。
  5. 研究一下 += 這個簡寫操作符的作用,寫一個腳本,把這個操作符用在里邊試一下。

Project Versions

Table Of Contents

Previous topic

習題 19: 函數(shù)和變量

Next topic

習題 21: 函數(shù)可以返回東西

This Page