2011-08-02 6 views
1

私は少し調べることにしました。私はthis bookがそれを読み始め、それからいくつかの練習をしたことが分かった。今、私は第6章でちょうどhereで立ち往生しています。 初心者の質問に申し訳ありませんが、このテスト()の機能はどこから来ますか?test() - Pythonの関数ですか? "コンピュータ科学者のように考える方法"を予約する

def mysum(xs): 
    """ Sum all the numbers in the list xs, and return the total. """ 
    running_total = 0 
    for x in xs: 
     running_total = running_total + x 
    return running_total 

#add tests like these to your test suite ... 
test(mysum([1, 2, 3, 4]), 10) 
test(mysum([1.25, 2.5, 1.75]), 5.5) 
test(mysum([1, -2, 3]), 2) 
test(mysum([ ]), 0) 
test(mysum(range(11)), 55) # Remember that 11 is not in the list that range generates. 

私はそれを見つけることができないようで、その本の前半では言及されていません。私はtestという名前のモジュールしか見つけませんでした。今私は混乱している、私は何かが不足している?第6章でこの関数を使用しないPython 2.x用のこの本のバージョンもあります.... 初心者に教えてください。そしてこの奇妙な質問についてもう一度申し訳ありません。

答えて

2

リンクされた章のSection 6.7にあります。

def test(actual, expected): 
    """ Compare the actual to the expected value, 
     and print a suitable message. 
    """ 
    import sys 
    linenum = sys._getframe(1).f_lineno # get the caller's line number. 
    if (expected == actual): 
     msg = "Test on line {0} passed.".format(linenum) 
    else: 
     msg = ("Test on line {0} failed. Expected '{1}', but got '{2}'." 
            . format(linenum, expected, actual)) 
    print(msg) 
+0

は、[OK]を行使する。これは私が読んでいたバージョンには存在しません。比較:[標準](http://openbookproject.net/thinkcs/python/english3e/index.html)と[RLE Edition](http://openbookproject.net/thinkcs/python/english3e-rle/index.html)アー。 – pythonn00b

1

第12章[辞書]にも同じ問題があります。もう一つの回避策があります。

def test(expression1, expression2): 
    if expression1 == expression2: 
     return 'Pass' 
    else: 
     return 'Fail' 

これは、すべてあなたが記載されている表現だけでなく、第12章[辞書]に記載されているもののために働く特別2.

関連する問題