Week Four: Good Programming Practices
-
Testing and Debugging
-
Classes of Tests
- break program into modules
- document constraints on modules
- document assumptions
-
Bugs
-
Debugging
-
Debugging Skills
-
Exceptions
-
Syntax: try;except;finally
try: a = int(input("tell me one number:")) b = int(input("tell me another number:")) print(a/b) print('okay') except ValueError: print('Bug in user input.') except ZeroDivisionError: print("Can't divide by zero") finally print('Close') print('outside')
-
Syntax: raise
我们可以使用raise语句自己触发异常。
# 定义函数 def mye( level ): if level < 1: raise Exception,"Invalid level!" # 触发异常后,后面的代码就不会再执行 try: mye(0) # 触发异常 except Exception,err: print 1,err else: print 2
- Use an assert statement to raise an
AssertionError
exception if assumptions not met.
def avg(grades):
assert not len(grades) == 0, 'no grades data'
return sum(grades)/len(grades)#raises an AssertionError if it is given an empty list for grades; otherwise runs ok
-
typically used to check inputs