MITx - 6.00.1x 笔记(4) Good Programming Practices

 

 

7 Testing and Debugging

防御性编程

DefensiveProgramming

  • 一开始设计程序时就要考虑到应当便于testing和debugging
  • 把程序分割成可以分别测试和调试的的几个小部分
  • 在程序的开头要注释,来说明程序的输入和输出
  • 代码间注释
    instruction
测试的几种情况

正确的测试顺序
1. 单元测试
2. 回归测试
3. 集成测试
很多人会急于运行整个程序进行测试,很容易出bug。正确的做法是从小到大一步步测试。
ClassesOfTests

测试的几个角度:

  • 直觉
  • 随机测试
  • 黑盒测试(基于功能)
  • 白盒测试(通过源代码)
    TestingApproaches

黑盒测试
Black Box Testing
白盒测试
White Box Testing

Bugs
  • Overt 显性 vs. Covert 隐性
  • Persistent 持续 vs. Intermittent 间歇
  • 隐性和间歇性的bugs很难找
    Categories of Bugs
Debugging
  • steep learning curve 陡峭的学习曲线
  • goal is to have a bug-free program
  • tools
    • built in to IDLE and Anaconda
    • Python Tutor
    • print statement
    • use your brain, be systematic in your hunt

Logic errors - Hard

  • think before writing new code
  • draw pictures, take a break
  • explain (not just read) the code

Don’t and Do
DONT&DO

8 Exceptions and Assertions

python常见错误类型
  AttributeError:属性错误,特性引用和赋值失败时会引发属性错误
  NameError:试图访问的变量名不存在
  SyntaxError:语法错误,代码形式错误
  IOError:输出输入错误
  KeyError:使用了映射中不存在的关键字(键)时引发的关键字错误
  IndexError:索引错误
  TypeError:类型错误
  ZeroDivisonError:除数为0错误
  ValueError:值错误
  

try, except, else, finally

  • 能够顺利执行try语句时才执行else语句,如果出现exception则不执行else
  • 总是要执行finally

Other Exceptions
  
手动设置需要抛出的错误提示

Exceptions as Control Flow
  

Assertions

用断言来确认某些期望的情况
Assertions

def avg(grades):
    assert not len(grades) == 0, 'no grades data' # 如果grades为空,抛出提示
    return sum(grades)/len(grades)

ApplyAssertions

可以使用assertions来及时指出不符合条件的地方,而不用手动添加各种print来寻找bug,可以用于检查输入输出是否符合要求

    
whereToUseAssertions
可以使用assertions来检查数据种类、数据结构、限制条件是否符合要求


练习题笔记:

d.get(key,default)
如果字典d中有指定的key,返回其对应的值;否则返回default。如果没有指定default,则返回None

===>这样可以避免从字典中取值时抛出KeyError

 例如:

def getFrequencyDict(sequence):
    """
    Returns a dictionary where the keys are elements of the sequence
    and the values are integer counts, for the number of times that
    an element is repeated in the sequence.

    sequence: string or list
    return: dictionary
    """
    # freqs: dictionary (element_type -> int)
    freq = {}
    for x in sequence:
        freq[x] = freq.get(x,0) + 1  # 统计频次的简洁代码,且可避免抛出KeyError
    return freq

   
Mutable Sequence Types

operationresult
s.clear()removes all items from s (same as del s[:])
s.copy()creates a shallow copy of s (same as s[:])

  
===>可以使用.copy()方法来复制字典

print(content, end=someting)
end表示print将如何结束,默认为end=”\n”。

In:

print('Hello', end=' ')
print('world', end='')
print('!')

Out:

Hello world!

转载于:https://www.cnblogs.com/huidanz/p/8543239.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值