- Python王者归来
- 洪锦魁
- 1453字
- 2020-08-28 21:54:53
7-4 while循环
这也是一个循环,基本上循环会一直执行直到条件运算为False才会离开循环,所以设计while循环时一定要设计一个条件可以离开循环,相当于让循环结束。程序设计时,如果忘了设计条件可以离开循环,程序造成无限循环状态,此时可以同时按Ctrl+C键,中断程序的执行离开无限循环的陷阱。
一般while循环常应用在不知道循环何时可以结束的状况,for循环在使用时是早已经知道循环即将执行的次数。不过我们也可以透过一些技巧,让while循环也可以应用在已经知道循环即将执行的次数上。它的语法格式如下:
while 条件运算: 程序区块
下列是while循环语法流程图。

7-4-1 基本while循环
程序实例ch7_26.py:这个程序会输出你所输入的内容,当输入q时,程序才会执行结束。

执行结果

上述程序最大的缺点是,当输入q时,程序也将输出q,然后才结束while循环,我们可以使用下列第8行增加if条件判断方式改良。
程序实例ch7_27.py:改良程序ch7_26.py,当输入q时,不再输出q。

执行结果

上述程序尽管可以完成工作,但是当我们在设计大型程序时,如果可以有更明确的标记记录程序是否继续执行将更佳,下列笔者将用一个布尔变量值active当作标记,如果是True则while循环继续,否则while循环结束。
程序实例ch7_28.py:改良ch7_27.py程序的可读性,使用标记active记录是否循环继续。

执行结果 与ch7_27.py相同。
程序实例ch7_29.py:猜数字游戏,程序第2行用变量answer存储欲猜的数字,程序执行时用变量guess存储所猜的数字。

执行结果

下列是使用while循环,已经知道要执行多少次循环了的实例。
程序实例ch7_30.py:while循环索引值变化的观察。

执行结果

7-4-2 嵌套while循环
while循环也允许嵌套循环,此时的语法格式如下:
while 条件运算: # 外层while循环 … while 条件运算:# 内层while循环 …
程序实例ch7_31.py:使用while循环重新设计ch7_19.py,打印九九乘法表。

执行结果 与ch7_19.py相同。
7-4-3 强制离开while循环-break指令
7-3-2节所介绍的break指令与观念,也可以应用在while循环。在设计while循环时,如果期待某些条件发生时可以离开循环,可以在循环内执行break指令立即离开循环,这个指令通常是和if语句配合使用。下列是常用的语法格式:

程序实例ch7_32.py:这个程序会先建立while无限循环,如果输入q,则可跳出这个while无限循环。程序内容主要是要求输入水果,然后输出此水果。

执行结果

程序实例ch7_33.py:使用while循环重新设计ch7_22.py。

执行结果 与ch7_22.py相同。
上述程序第6行的“index < len(players)”相当于是语法格式的条件表达式A,控制循环是否终止。程序第7行的“index == n”相当于是语法格式的条件表达式B,可以控制是否中途离开while循环。
7-4-4 while循环暂时停止不往下执行-continue指令
在设计while循环时,如果期待某些条件发生时可以不往下执行循环内容,此时可以用continue指令,这个指令通常是和if语句配合使用。下列是常用的语法格式:

程序实例ch7_34.py:列出1至10之间的偶数。

执行结果

7-4-5 while循环条件表达式与对象
while循环的条件表达式也可与对象(列表、元组或字典)配合使用,此时它的语法格式如下:
while 条件表达式:# 与有关的条件表达式
程序区块
程序实例ch7_35.py:删除列表内的apple字符串,程序第5行,只要在fruits列表内可以找到变量apple,就会传回True,循环将继续。

执行结果

程序实例ch7_36.py:有一个列表buyers,此列表内含购买者和消费金额,如果购买金额超过或达到1000元,则归类为VIP买家vipbuyers列表。否则是Gold买家goldbuyers列表。

执行结果

上述程序第9行只要列表不是空列表,while循环就会一直执行。
7-4-6 pass
pass指令是什么事也不做,如果我们想要建立一个无限循环可以使用下列写法。
while True: pass
不过不建议这么做,这会让程序进入无限循环。这个指令有时候会用在设计一个循环或函数(将在第11-8节解说)尚未完成时,先放pass,未来再用完整程序代码取代。
程序实例ch7_37.py:pass应用在循环的实例,这个程序的循环尚未设计完成,所以笔者先用pass处理。

执行结果 没有任何数据输出。