前言

while是一种循环模式,当满足条件时进入循环,当条件不满足时跳出循环,for循环用于针对集合中的每个元素都一个代码块,而while循环不断地运行,直到指定的条件不满足为止。

while循环
number = 1
while number <= 5:
	print(number)
	number += 1
break停止循环
number = 1
while number <= 5:
	print(number)
	number += 1
	if number == 3:
		break
continue跳出当前循环
number = 0
while number < 10:
	number += 1
	if number % 2 == 0:
		continue
	
	print(number)
在列表间移动元素
unconfirmed_users = ['alice', 'brian', 'candace']
confirmed_users = []

# 此处对列表对象使用while,当list为空时while判断为False
while unconfirmed_users:  
	current_user = unconfirmed_users.pop()
	confirmed_users.append(current_user)

for confirmed_user in confirmed_users:
	print(confirmed_user.title())
删除包含特定值的所有列表元素
pets = ['dog', 'cat', 'dog', 'glodfish', 'cat', 'rabbit', 'cat']
print(pets)

while 'dog' in pets:
	pets.remove('dog')

print(pets)
- End -
一个努力中的公众号
关注一下吧
Python基础之while_javascript
 
作者:Maggieq8324