
5.7 循环控制语句
循环语句主要是在满足条件的情况下反复执行某一个操作。循环控制语句主要包括while语句和for语句。
5.7.1 while语句
while语句是循环语句,也是条件判断语句。
while语句语法格式如下:

这里同样需要注意冒号和缩进。
下面通过一个示例计算1~20的总和。
【例5.8】使用while循环语句(源代码\ch05\5.8.py)。

保存并运行程序,结果如图5-24所示。

图5-24 运行结果
注意 如果在这里遗漏代码行b+= 1,程序就会进入无限循环中。因为变量b的初始值为1,并且不会发生变化,所以b <= a始终为Ture,导致while循环不会停止。
要避免无限循环的问题,就必须对每个while循环进行测试,确保其会按预期的那样结束。如果希望程序在用户输入特定值时结束,那么可运行程序并输入这样的值;如果在这种情况下程序没有结束,那么请检查程序处理这个值的方式,确认程序至少有一个这样的地方能让循环条件变为False,或者让break语句得以执行。
如果条件表达式一直为Ture,while循环就会进入无限循环中。无限循环应用也比较广泛,如在服务器上处理客户端的实时请求时就非常有用。
【例5.9】while无限循环中的应用(源代码\ch05\5.9.py)。

保存并运行程序,结果如图5-25所示。

图5-25 运行结果
如果用户想退出无限循环,可以按Ctrl+C组合键。
当while循环体中只有一条语句时,可以将该语句与while写在同一行中。例如:
aa = "商品" while aa=="商品" :print ("这里只有一条执行语句") print ("商品采购完毕!")
while语句可以和else配合使用,表示当while语句的条件表达式为False时,执行else的语句块。
【例5.10】while语句和else配合使用(源代码\ch05\5.10.py)。

保存并运行程序,结果如图5-26所示。

图5-26 运行结果
5.7.2 for语句
for语句通常由条件控制和循环两部分组成。
for语句语法格式如下:

其中,<variable>是一个变量名称;<sequence>是一个列表。else语句运行的时机是当for语句都没有运行,或者最后一个循环已经运行时。else语句是可以省略的。
下面实例打印变量n所有的值:
for n in [100,200,300,400,500,600,700,800,900]: print (n)
执行结果如图5-27所示。

图5-27 运行结果
下面实例打印变量a1,a2所有的值:
>>>a= [(100,200),(300,400),(500,600)] >>>for a1,a2 in a:print (a1,a2)
执行结果如图5-28所示。

图5-28 运行结果
若想跳出循环,则可以使用break语句,该语句用于跳出当前循环体。
【例5.11】for语句和break语句的配合使用(源代码\ch05\5.11.py)。

保存并运行程序,结果如图5-29所示。从结果可以看出,当搜索到西瓜时,会跳出当前循环,对应的循环else块将不执行。

图5-29 运行结果
5.7.3 continue语句和else语句
使用continue语句,Python将跳过当前循环块中的剩余语句,继续进行下一轮循环。
【例5.12】for语句和continue语句的配合使用(源代码\ch05\5.12.py)。

保存并运行程序,结果如图5-30所示。从结果可以看出,当变量为80时,将跳出当前循环,进入下一个循环中。

图5-30 运行结果
当for循环被执行完毕或while循环条件为False时,else语句才会被执行。需要特别注意的是,如果循环被break语句终止,那么else语句不会被执行。
【例5.13】for、break和else语句的配合使用(源代码\ch05\5.13.py)。

保存并运行程序,结果如图5-31所示。从结果可以看出,当搜索到文字“不”时,将通过break语句跳出循环。

图5-31 运行结果
5.7.4 pass语句
pass是空语句,主要为了保持程序结构的完整性。pass不做任何事情,一般用作占位语句。
【例5.14】for和pass语句配合使用实例(源代码\ch05\5.14.py)。

保存并运行程序,结果如图5-32所示。从结果可以看出,当搜索到文字“鱼”时,先执行print ('执行pass语句'),然后执行print ('当前文字:', a)。

图5-32 运行结果