Introduction to Computer Science and Programming Using Python(4)

 

Week Four: Good Programming Practices

  1. Testing and Debugging

    mark

  2. Classes of Tests

    • break program into modules
    • document constraints on modules
    • document assumptions
    • mark
    • mark
    • mark
    • mark
    • mark
  3. Bugs

    • mark
  4. Debugging

    • mark
    • mark
    • mark
    • mark
    • mark
    • mark
  5. Debugging Skills

    • mark
    • mark
    • mark
  6. 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

  • mark