MITx - 6.00.1x 笔记(4) Good Programming Practices
7 Testing and Debugging
防御性编程
- 一开始设计程序时就要考虑到应当便于testing和debugging
- 把程序分割成可以分别测试和调试的的几个小部分
- 在程序的开头要注释,来说明程序的输入和输出
- 代码间注释 
 
测试的几种情况
正确的测试顺序: 
1. 单元测试 
2. 回归测试 
3. 集成测试 
很多人会急于运行整个程序进行测试,很容易出bug。正确的做法是从小到大一步步测试。 
测试的几个角度:
- 直觉
- 随机测试
- 黑盒测试(基于功能)
- 白盒测试(通过源代码) 
 
黑盒测试 
 
白盒测试 
Bugs
- Overt 显性 vs. Covert 隐性
- Persistent 持续 vs. Intermittent 间歇
- 隐性和间歇性的bugs很难找 
 
Debugging
- steep learning curve 陡峭的学习曲线
- goal is to have a bug-free program
- tools 
 - built in to IDLE and Anaconda
- Python Tutor
- printstatement
- 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 
8 Exceptions and Assertions
python常见错误类型: 
  AttributeError:属性错误,特性引用和赋值失败时会引发属性错误 
  NameError:试图访问的变量名不存在 
  SyntaxError:语法错误,代码形式错误 
  IOError:输出输入错误 
  KeyError:使用了映射中不存在的关键字(键)时引发的关键字错误 
  IndexError:索引错误 
  TypeError:类型错误 
  ZeroDivisonError:除数为0错误 
  ValueError:值错误 
  
try, except, else, finally
- 能够顺利执行try语句时才执行else语句,如果出现exception则不执行else
- 总是要执行finally
 
   
手动设置需要抛出的错误提示
 
  
Assertions
用断言来确认某些期望的情况 
def avg(grades):
    assert not len(grades) == 0, 'no grades data' # 如果grades为空,抛出提示
    return sum(grades)/len(grades)可以使用assertions来及时指出不符合条件的地方,而不用手动添加各种print来寻找bug,可以用于检查输入输出是否符合要求
     
 
可以使用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| operation | result | 
|---|---|
| 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! 
                    
                     
                    
                 
                    
                

 
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号