File tree Expand file tree Collapse file tree 1 file changed +6
-8
lines changed Expand file tree Collapse file tree 1 file changed +6
-8
lines changed Original file line number Diff line number Diff line change 2
2
3
3
#错误和异常(3)
4
4
5
- 按照一般的学习思路,掌握了前两节内容,已经足够编程所需了。但是,我还想再多一步,还是因为本教程的读者是要from beginner to master。
5
+ ###assert
6
6
7
- ## assert
7
+ 从代码中理解 ` assert ` 。
8
8
9
9
>>> assert 1==1
10
10
>>> assert 1==0
11
11
Traceback (most recent call last):
12
12
File "<stdin>", line 1, in <module>
13
13
AssertionError
14
14
15
- 从上面的举例中可以基本了解了assert的特点 。
15
+ assert,翻译过来是“断言”之意。 ` assert ` 是一句等价于布尔真的判定,发生异常就意味着表达式为假 。
16
16
17
- assert,翻译过来是“断言”之意。assert是一句等价于布尔真的判定,发生异常就意味着表达式为假。
18
-
19
- assert的应用情景就有点像汉语的意思一样,当程序运行到某个节点的时候,就断定某个变量的值必然是什么,或者对象必然拥有某个属性等,简单说就是断定什么东西必然是什么,如果不是,就抛出错误。
17
+ ` assert ` 的应用情景就有点像汉语的意思一样,当程序运行到某个节点的时候,就断定某个变量的值必然是什么,或者对象必然拥有某个属性等,简单说就是断定什么东西必然是什么,如果不是,就抛出异常。
20
18
21
19
#!/usr/bin/env python
22
20
# coding=utf-8
@@ -35,9 +33,9 @@ assert的应用情景就有点像汉语的意思一样,当程序运行到某
35
33
if amount <= self.balance:
36
34
self.balance -= amount
37
35
else:
38
- print "balance is not enough."
36
+ print "balance is not enough." #Python 3: print("balance is not enough.")
39
37
40
- 上面的程序中,deposit()和withdraw()方法的参数amount值必须是大于零的 ,这里就用断言,如果不满足条件就会报错。比如这样来运行:
38
+ 上面的程序中,` deposit() ` 和 ` withdraw() ` 方法的参数 ` amount ` 必须是大于零的 ,这里就用断言,如果不满足条件就会报错。比如这样来运行:
41
39
42
40
if __name__ == "__main__":
43
41
a = Account(1000)
You can’t perform that action at this time.
0 commit comments