1.标志
prompt = '\nTell me something,and I will repeat it back to you:'
prompt += '\nEnter "quit" to end the program.'
active = True
#这里active就是一个标志。常用于简化while语句,不用在每一句while执行后都判断。
while active:
message = input(prompt)
if message == 'quit':
active = False
else:
print(message)
2.continue
current_number = 0
while current_number <10:
current_number += 1
if current_number % 2 == 0:
continue
print(current_number)
3.在列表之间移动元素。此处使用while循环来实现。
#在列表之间移动元素
unconfirmed_users = ['a','o','e']
confirmed_users = []
while unconfirmed_users:
current_users = unconfirmed_users.pop()
print("Verifying user:"+ current_users.title())
confirmed_users.append(current_users)
print("\nThe following users have been confirmed:")
for confirmed_user in confirmed_users:
print(confirmed_user.title())
先创建一个未验证用户列表,其中包含aoe,再创建一个空列表,用于存储已验证的用户。 while循环依次执行,直到列表变成空的。pop()从列表尾弹出元素,转存到current_user中。
4.使用用户输入来填充字典
#使用用户输入来填充字典
responses = {}
#回答
#设置一个标志,指出调查是否继续
polling_active = True
while polling_active:
name = input("\nWhat is your name? ")
response = input("Which number do you like best?")
#将答案存储在字典中
responses[name] =response
#看看是否还有人要参与调查
repeat = input("Whould you like to let another person respond?(Y/N)")
if repeat =='N':
polling_active = False
#调查结束,显示结果
print("\n-----Poll results----")
for name,response in responses.items():
print(name +' would preffer '+ response + '.')
运行结果:
What is your name? a
Which number do you like best?1
Whould you like to let another person respond?(Y/N)Y
What is your name? a
Which number do you like best?2
Whould you like to let another person respond?(Y/N)y
What is your name? a
Which number do you like best?3
Whould you like to let another person respond?(Y/N)n
What is your name? c
Which number do you like best?3
Whould you like to let another person respond?(Y/N)N
-----Poll results----
a would preffer 3.
c would preffer 3.
分析:
如果同名,会变成直接修改上一个。而不会添加为新的项。
大小写不等价