<dd id="sga4y"><optgroup id="sga4y"></optgroup></dd>
<nav id="sga4y"><code id="sga4y"></code></nav>
  • <optgroup id="sga4y"></optgroup>

    習題 20: 函數和文件?

    回憶一下函數的要點,然后一邊做這節練習,一邊注意一下函數和文件是如何在一起協作發揮作用的。

     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 時,我們是怎樣傳遞當前的行號信息的。

    你應該看到的結果?

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

    Project Versions

    Table Of Contents

    Previous topic

    習題 19: 函數和變量

    Next topic

    習題 21: 函數可以返回東西

    This Page

    97av