# 7.2 while循环简介
for 循环--用于针对集合中的每个元素都执行一个代码块
while 循环--则不断运行,直到指定的条件不满足为止
## 7.2.1 使用while循环
例子:从1开始递增,大于5就停止递增
current_number = 1
while current_number <= 5:
print(current_number)
current_number += 1
## 7.2.2 让用户选择何时退出,设定退出值
message = ""
message = []
message = {}
prompt = "\n Tell ne something,and I will repeat it back to you : "
prompt += "\n Enter 'quit' to end the program."
message = ""
while message != 'quit': #等于quit也为结束条件
message = input(prompt)
if message != 'quit': # if 不等于quit时候又输出值,等于时候无输出值
print(message)
## 7.2.3 使用标志
prompt = "\n Tell ne something,and I will repeat it back to you : "
prompt += "\n Enter 'quit' to end the program."
active = True
while active:
message = input(prompt)
if message == 'quit': #if语句检出值
active =False #while循环不再运行
else:
print(message)
## 7.2.4 使用break 退出循环
在任何循环中都可以使用 break 语句
prompt = "\n Tell ne something,and I will repeat it back to you : "
prompt += "\n Enter 'quit' to end the program."
while True:
city = input(prompt)
if city == 'quit':
break #退出循环
else:
print(f"I'd love go to {city.title()}!")
## 7.2.5 在循环中使用continue
break --不执行余下的代码,退出整个循环
continue--不执行余下的代码,返回循环开头
例子:从1~10,打印奇数的循环
current_number = 0
while current_number < 10:
current_number += 1
if current_number % 2 == 0:
continue #为0是偶数,跳过不打印
print(current_number) #打印剩下的偶数
## 7.2.6 避免无限循环
x = 1
while x <= 5:
print(x)
x += 1
# 7.3 使用while 循环处理列表和字典
## 7.3.1 在列表之间移动元素
假设有一个列表包含信新注册但还未验证的用户网站
unconfirmed_users = ['alive','brian','candace']
验证这些用户后,如何将他们移动到另一个已验证用户列表中呢?
confirmed_users = []
办法是使用一个while循环,在验证用户的同时将其从未验证用户列表中提取出来,再将其加入另一个已验证用户列表中
#首先,创建一个未验证用户列表
#和一个用于存储已验证用户的空列表
unconfirmed_users = ['alive','brian','candace']
confirmed_users = []
#验证每个用户,直到没有未验证用户为止
#将每个经过验证的用户都移到已验证用户列表中
while unconfirmed_users:
current_user = unconfirmed_users.pop() #pop每次从列表跳出一个元素
print(f"Verifying user: {current_user.title()}")
confirmed_users.append(current_user) #append添加元素到列表
#显示已验证用户
print(f"\nThe following users have been confirmed: ")
for confirmed_user in confirmed_users:
print(confirmed_user.title())
## 7.3.2 删除为特定值的所有列表元素
移除cat
pets = ['dog','cat','goldfish','cat','rabbit','cat']
print(pets)
while 'cat'in pets:
pets.remove('cat')
print(pets)
## 7.3.3 使用用户输入来填充字典
responses = {} #空字典
polling_active = True #标志
while polling_active:
name = input("\nWhat is you name? ") #键
response = input("Which mountain would you like to climb someday?") #值
responses[name] = response #形成键值对 存入字典
repeat = input("Would you like to iet another person response ? (yes/no)")
if repeat == "no":
polling_active = False #t退出循环的标志
#调查结束,显示结果
print("\n ---Poll Results--")
for name,response in responses.items(): #字典的循环items()
print(f"{name} would like to climb {response}")
python基础:六,while
于 2023-07-15 22:02:01 首次发布