1.6 Python语句与函数
1.6.1 条件判断语句
在编程的过程中,经常会遇到各种逻辑判断。Python提供if条件判断语句实现程序的逻辑判断。if条件判断语句是通过一条或多条语句的执行结果(true或false)来决定执行的代码块。Python中的if语句用于控制程序的执行,基本格式如下。

【例1-33】基本条件判断示例。

如果是多条件判断,则需要使用如下格式。

【例1-34】多条件判断示例。

由于Python并不支持switch语句,所以多个条件判断只能用elif来实现。如果需要多个条件同时判断时,可以使用or(或),表示两个条件有一个成立时判断条件成立;使用and(与),表示只有两个条件同时成立的情况下,判断条件才成立。
【例1-35】同时判断多个条件示例。

1.6.2 循环语句
Python中提供了两种主要的循环语句:for和while。
1.for循环
Python中的for循环可以遍历任何序列的项目,如一个列表或一个字符串,直到遍历完为止。
for循环语句的格式如下。

【例1-36】遍历列表示例。

【例1-37】遍历集合示例。


【例1-38】遍历字典示例。

2.while循环
Python中的while语句用于循环执行程序,即在某条件下,循环执行某段程序,以处理需要重复处理的相同任务。其基本格式如下。

执行语句可以是单个语句或代码块。判断条件可以是任何表达式,任何非零或非空(null)的值均为true。当判断条件为false时,循环结束。
【例1-39】while循环遍历小于10的数字示例。

1.6.3 自定义函数
函数是组织好的、可重复使用的、用来实现单一或相关联功能的代码块。函数能提高应用的模块性和代码的重复利用率。函数是具有名字的代码块,能够被程序根据实际需求进行调用,从事不同的具体工作。
自定义一个满足特定功能的函数,其规则如下。
① 函数代码块以def关键字开头,后接函数标识符名称和圆括号“()”。
② 任何传入参数和自变量必须放在圆括号中。
③ 函数的第一行语句可以有选择地使用文档字符串,用于存放函数说明。
④ 函数内容以冒号起始,并且缩进。
⑤ 函数中的return[表达式]表示有选择地返回一个值给调用方。不带表达式的return相当于返回None。
Python的函数分为自定义函数和内置函数,Python中有很多内置函数,如print()等。下面我们来自定义简单的函数。
【例1-40】自定义不带参数和带参数的函数示例。

【例1-41】自定义不带return和带return的函数示例。
