最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

習(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)前的行號信息的。

你應(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ù)沒有用錯(cuò)。
  4. 上網(wǎng)研究一下 file 中的 seek 函數(shù)是做什么用的。試著運(yùn)行 pydoc file 看看能不能學(xué)到更多。
  5. 研究一下 += 這個(gè)簡寫操作符的作用,寫一個(gè)腳本,把這個(gè)操作符用在里邊試一下。

Project Versions

Table Of Contents

Previous topic

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

Next topic

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

This Page

木兰县| 舒兰市| 天气| 信阳市| 新津县| 清远市| 东乡| 白城市| 翁源县| 凤阳县| 喀什市| 秦皇岛市| 肃北| 深水埗区| 炉霍县| 莱芜市| 鹰潭市| 高尔夫| 株洲县| 灵丘县| 来宾市| 航空| 德庆县| 斗六市| 日照市| 蒲城县| 信宜市| 白沙| 吴旗县| 灵石县| 竹山县| 云林县| 定远县| 渝北区| 阿克陶县| 遵化市| 铜陵市| 台南市| 巴林右旗| 东安县| 德阳市|