亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

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

回憶一下函數(shù)的要點(diǎn),然后一邊做這節(jié)練習(xí),一邊注意一下函數(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)

特別注意一下,每次運(yùn)行 print_a_line 時(shí),我們是怎樣傳遞當(dāng)前的行號(hào)信息的。

你應(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.

$

加分習(xí)題?

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

Project Versions

Table Of Contents

Previous topic

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

Next topic

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

This Page