https://blog.csdn.net/a5322143/article/details/102378276
到目前为止,我们编写的程序都是简单的按语句顺序一条一条执行的。本节将介绍
让程序选择执行语句的方法。
如果条件(在if和冒号之间的表达式)判 定为真,那么后面的语句块(本例中是
print语句)就会被执行;如果条件为假, 语句块就不会被执行。
在else子句的示例中,假如除if条件外,还有多个
子条件需要进行判定,该怎么处理?
Python为我们提供了一个elif语句,elif是“else if”
的简写,意思为具有条件的else子句。
所谓嵌套代码,就是把if、else、elif些条件语句再放入到if、else、
elif这些条件的语句块中,作为更深一层 次的条件判定语句。
● 在Python中,有一个和if语句工作方式非常相近的关键字,
其工作方式类似如下伪代码:
● if not condition:
● crash program
● 在没完善一个程序之前,我们不知道程序在哪里会出错,与
其让它在运行时崩溃,不如在出现错误条件时就崩溃。一般
来说,可以要求某些条件必须为真。在Python中,assert关
键字能实现这个工作方式。先来看一个示例:
● >>> x=3
● >>> x > 0, "x is not zero or assert negative"
● >>> assert x%2 == 0, "x is not an even number" #提示x不
是偶数
● Traceback (most recent call last):
● File "<pyshell#81>", line 1, in <module>
● assert x%2 == 0, "x is not an even number"
● AssertionError: x is not an even number
网友评论