# CS61A 系列课程笔记（一）

xiaoxiao2021-02-28  15

**********************正文*********************** 看到函数一节，reading 1.5材料中 介绍了对函数的测试 主要讲了三种： 1. assert 不太常用 以斐波那契数列为例下一个函数

>>> def fib(n): # n>2 ... a,b=0,1 ... for i in range(2,n+1): ... a,b=b,a+b ... return b ... >>> fib(4) 3 >>> fib(5) 5 >>> fib(6) 8 >>> assert fib(6)==8,'the sixth number should be 8,whis content will be returned when error' >>> assert fib(6)==7,'this is not right i just try to see what will happen when error' Traceback (most recent call last): File "<stdin>", line 1, in <module> AssertionError: this is not right i just try to see what will happen when error >>>

2.第二种是在函数中写入一些信息，当我们调用doctest的testmod方法时就会返回

>>> def sum_num(n): ... """this code is to cal the sum of the n numbers ... >>> sum_num(10) ... 55 ... >>> sum_num(100) ... 5050 ... """ ... total,k=0,1 ... for i in range(n): ... total,k=total+k,k+1 ... return total ... >>> from doctest import testmod >>> testmod() TestResults(failed=0, attempted=2)

3.第三种也是导入doctest模块的一个函数，该函数为run_docstrig_examples 这个函数在调用的时候需要传入参数，第一个参数是被测试的函数名，第二个参数是globals() 这是固定的，第三个参数是True表示把具体的信息都展示出来

>>> def sum(x,y): ... """this function is to cal the sum of two given numbers ... >>> sum(1,2) ... 3 ... >>> sum(3,4) ... 7 ... """ ... return x+y ... >>> from doctest import run_docstring_examples >>> run_docstring_examples(sum,globals(),True) Finding tests in NoName Trying: sum(1,2) Expecting: 3 ok Trying: sum(3,4) Expecting: 7 ok

3.又自己写了一个函数，带有测试的哦

# -*- coding: utf-8 -*- """ Created on Sun May 6 20:41:21 2018 @author: Administrator """ def sum_num_xuanxuan(n,times): """this function is to cal two sub_function with different features----xuanxan >>> sum_num_xuanxuan(5,3) 225 >>> sum_num_xuanxuan(5,1) 15 """ total,k=0,1 while k<=n: total,k=total+pow(k,times),k+1 return total

from doctest import testmod testmod() Out[3]: TestResults(failed=0, attempted=2) from doctest import run_docstring_examples run_docstring_examples(sum_num_xuanxuan,globals(),True) Finding tests in NoName Trying: sum_num_xuanxuan(5,3) Expecting: 225 ok Trying: sum_num_xuanxuan(5,1) Expecting: 15 ok