python 编程小白 ,不会用doctest 请大神指教怎么用!!
发布网友
发布时间:2022-05-10 23:59
我来回答
共4个回答
热心网友
时间:2022-05-11 01:28
三个引号是python里面一种字符串,写在函数里面是函数的帮助文档,你用help(compare)查看这个函数就会输出
compare(x, y)
compare(5,4)
1
compare (7,7)
0
compare (2,3)
-1
这些你写在引号之间的帮助信息。还有是testmod(),你拼错了。
不过你这样写法不能被doctest识别,你应该在每个测试的例子前面加上>>>,所以正确的写法是
def compare(x,y):
"""
>>> compare(5,4)
1
>>> compare (7,7)
0
>>> compare (2,3)
-1
"""
if x>y:
return 1
elif x==y:
return 0
else :
return -1
if __name__=='__main__':
import doctest
doctest.testmod()
这样运行python compare.py -v就会输出
Trying:
compare(5,4)
Expecting:
1
ok
Trying:
compare (7,7)
Expecting:
0
ok
Trying:
compare(2,3)
Expecting:
-1
ok
1 items had no tests:
__main__
1 items passed all tests:
3 tests in __main__.compare
3 tests in 2 items.
3 passed and 0 failed.
Test passed.
热心网友
时间:2022-05-11 02:46
>>>
>>> def is_between(v, lower, higher):
... '''demo of doctest
... >>> is_between(5,1,9)
... True
... >>> is_between(3,3,9)
... False
... '''
... return lower<v<higher
...
>>> if __name__=='__main__':
... import doctest
... doctest.testmod(verbose=True)
...
Trying:
is_between(5,1,9)
Expecting:
True
ok
Trying:
is_between(3,3,9)
Expecting:
False
ok
1 items had no tests:
__main__
1 items passed all tests:
2 tests in __main__.is_between
2 tests in 2 items.
2 passed and 0 failed.
Test passed.
TestResults(failed=0, attempted=2)
>>>
示例代码贴给你,希望对你能有帮助
另外doctest对已知的预期结果进行测试是非常方便的,有不明白的可以追加提问。
追问三个双引号之间需要填写什么? 引号后需要填写什么? 你的例子我懂了 但是运用到我的方程里时应该怎么写? 我的方程说是语法错误 不明白哪里错了
追答你的那个if __name__ == '__main__':这里有问题吧。。。看好了,那个是双下划线,你写的是但下划线吧
热心网友
时间:2022-05-11 04:21
"这样运行python compare.py -v就会输出',怎么运行啊?在哪个界面下运行,跟python版本和操作系统平台有关吗?