Python中的test()函数?书籍《如何像计算机科学家一样思考》
我决定稍微了解一下Python。我找到了一本书,开始阅读并做了一些练习。现在我卡在第六章,正好在这里。
抱歉我这个新手问了个问题,这个test()函数是从哪里来的呢?
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的模块。现在我有点困惑,是我漏掉了什么吗?这本书还有一个Python 2.x的版本,在第六章也没有使用这个函数……
请帮帮我这个新手,再次为这个奇怪的问题感到抱歉。
2 个回答
1
在第12章[字典]中也有同样的问题。这是另一个解决方法。
def test(expression1, expression2):
if expression1 == expression2:
return 'Pass'
else:
return 'Fail'
这个方法适用于你列出的所有表达式,以及第12章[字典]中提到的内容,特别是练习2。
2
它在链接章节的第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)