开发者

test()-function in python? Book "How to Think Like a Computer Scientist"

开发者 https://www.devze.com 2023-03-24 21:12 出处:网络
I decided to look a bit into python. I found this book began to read it and did some exercises from it. Now I\'m stuck at chapter 6, exactly here.

I decided to look a bit into python. I found this book began to read it and did some exercises from it. Now I'm stuck at chapter 6, exactly here. Sorry for my newbie question but where comes this test()-function from?

def mysum(xs):
    """ Sum all the numbers in the l开发者_C百科ist 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.

I can't seem to find it and its never mentioned earlier in the book. I only found a module named test. Now I'm kind of confused, am I missing something? There is also a version of this book for Python 2.x which does not use this function in Chapter 6.... Please enlighten a newbie and sorry again for this weird question.


Its in Section 6.7 of the linked chapter.

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)


Same issue in Chapter 12 [Dictionaries]. Here's another workaround.

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

This will work for all the expressions you listed as well as the ones listed in Chapter 12 [Dictionaries], specifically Exercise 2.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号