
书本5.3——if语句


Python条件语句是通过一条或多条语句的执行结果(True或者False)来决定执行的代码块。
三种基本程序结构中的选择结构:
1、if语句
2、if/else语句
3、if/elif/else语句
一、if语句
Python的if语句的功能跟其他语言的非常相似,都是用来判定给出的条件是否满足,然后根据判断的结果(即真或假)决定是否执行给出的操作。If语句是一种单选结构,它选择的是做与不做。它是由三部分组成:关键字if本身、测试条件真假的表达式和表达式结果为真时要执行的代码。

二、if/else语句
if/else语句是一种双选结构,它选择的不是做与不做的问题,而是在两种备选行动中选择哪一个的问题。if/else语句由五部分组成:关键字if、测试条件真假的表达式、表达式结果为真时要执行的代码,以及关键字else和表达式结果为假时要执行的代码。

if/else语句的四种写法:




三、if/elif/else语句
if/elif/else是一种多选结构——在多组动作中选择一组执行。该语句利用一系列条件表达式进行检查,并在某个表达式为真的情况下执行相应的代码。
注意:if/elif/else语句的备选动作较多,但是有且只有一组动作被执行

Python并不要求if/elif结构后面必须有else代码块。

网友评论