Python 学习笔记(九)——while应用

1. 第一个例子(在列表之间移动元素)

假设有一个列表,其中包含新注册但还未验证的网站用户名;验证这些用户后,如何将他们移到另一个已验证的用户列表中?一种办法是使用一个while循环,在验证用户的同时将其从未验证用户列表中提取出来,再放到已验证的列表中,代码可能类似这样:

1
2
3
4
5
6
7
8
9
10
11
unconfirmed_users = ['alice', 'brian', 'candace']
confirmed_users = []

while unconfirmed_users:
current_user = unconfirmed_users.pop()
print('Verifying user: ' + current_user.title())
confirmed_users.append(current_user)

print("\n已验证用户:")
for confirmed_user in confirmed_users:
print(confirmed_user.title())

2. 第二个例子

while 循环删除列表中特定元素。

1
2
3
4
5
6
7
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)

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

print(pets)

3. 第三个例子(使用用户输入来填充字典)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 首先创建一个空字典
responses = {}

# 设置一个标志,指出调查是否继续
active = True

while active:
# 提问名字和回答
name = input("\nWhat's your name?")
response = input("Which mountain would you like to climb someday?")

# 将回答存储在字典中
responses[name] = response

# 看看是否还有人要参与调查
repeat = input("Would you like to let another one respond?(yes/no)")
if repeat == 'no':
active = False

# 调查结束,显示结果
print("\n-- Poll Result --") # poll: 民意检测
for name, response in responses.items():
print(name + " would like to climb " + response + '.')
———— The End ————