断言assert
1 info = {} 2 info['name'] = 'alex' 3 # info['age'] = 18 4 5 if 'name' not in info: 6 raise KeyError('必须有name这个key') 7 if 'age' not in info: 8 raise KeyError('必须有age这个key') 9 10 结果为:11 12 Traceback (most recent call last):13 File "C:/Users/xu516/PycharmProjects/Python全栈开发/第三模块/面向对象编程/33 try...except详细用法.py", line 68, in14 raise KeyError('必须有age这个key')15 KeyError: '必须有age这个key'
断言是断定会有什么,没有的话就会报错,可以用assert方法来实现,如下:
1 info = {} 2 info['name'] = 'alex' 3 # info['age'] = 18 4 5 # if 'name' not in info: 6 # raise KeyError('必须有name这个key') 7 # if 'age' not in info: 8 # raise KeyError('必须有age这个key') 9 10 assert ('name' in info) and ('age' in info)11 12 结果为:13 14 Traceback (most recent call last):15 File "C:/Users/xu516/PycharmProjects/Python全栈开发/第三模块/面向对象编程/33 try...except详细用法.py", line 70, in16 assert ('name' in info) and ('age' in info)17 AssertionError
断言报错,
1 info = {} 2 info['name'] = 'alex' 3 info['age'] = 18 4 5 # if 'name' not in info: 6 # raise KeyError('必须有name这个key') 7 # if 'age' not in info: 8 # raise KeyError('必须有age这个key') 9 10 assert ('name' in info) and ('age' in info)11 12 if info['name'] == 'alex' and info['age'] > 10:13 print('welcome')14 15 结果为:16 17 welcome
if 语句的执行依赖于前面代码执行结果