for循环用于针对集合中的每一个元素都一个代码块,而while循环不断地运行,直到指定的条件不满足为止。
7.2.1 使用while循环
counting.py
current_number = 1
while current_number <= 5:
print(current_number)
current_number += 1
7.2.2 让用户选择何时退出
定义一个退出值,当用户输入的不是这个值,程序就接着运行。这是while循环的主要应用之一。
parrot.py
prompt = "\nTell me something, and I will repeat it back to you!"
prompt += "\nEnter 'quit' to end the program."
message = ""
while message != 'quit'
message = input(prompt)
print(message)
为避免该程序中将’quit’打印出来,只需使用一个简单的if测试,将print()语句改为:
if message != 'quit'
print(message)
7.2.3 使用标志
在复杂的程序中,很多不同的事件都会导致程序停止运行,此时再使用while()语句逐一检索就会变得十分麻烦。因此,我们可定义一个变量,这个变量被称为“标志”。令当标志为True时,程序继续运行;当标志为False时,程序停止运行。
例:
prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program. "
active = True
while active:
message = input(prompt)
if message == 'quit':
active = False
else:
print(message)
7.2.4 使用break退出循环
cities.py
prompt = "\nPlease enter the name of a city you have visited: "
prompt = "\n(Enter 'quit' when you are finished.)"
while(True)
city = input(prompt)
if city == 'quit':
break
else:
print("I'd love to go to " + city.title() + "!")
7.2.5 在循环中使用continue
counting.py
current_number = 0
while current_number < 10:
current_number += 1
if current_number % 2 == 0:
continue
print(current_number)
7.2.6 避免无限循环
每个while循环必须有停止运行的途径。