7.2 while循环简介

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循环必须有停止运行的途径。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值