首页 > 技术文章 > python assert用法

wq242424 2017-03-09 10:41 原文

assert的异常参数,其实就是在断言表达式后添加字符串信息,用来解释断言并更好的知道是哪里出了问题。

格式如下:
assert expression [, arguments]
assert 表达式 [, 参数]

举个例子:

  string = 'helloworld'

  assert 'world' in string,'输入的字符中不包含world'

  print ‘输入的字符中包含world’

  #执行下来会输出:输入的字符中包含world

若脚本改成:

  string = 'helloman'

  assert 'world' in string,'输入的字符中不包含world'

  print ‘输入的字符中包含world’

  #输出:AssertionError:输入的字符中不包含world

执行下来会输出AssertionError,来表明断言错误,以此可以让作者发现是什么地方出现的错误,而且下面的print语句不会执行。

 

推荐阅读