Python while循环

while循环

  • for循环针对于集合中每个元素的一个代码块,while循环不断地运行,直到指定的条件不满足为止。
  • 让用户选择何时退出
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)
    if message != 'quit':
        print(message)
Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. hello
hello

Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. nice to meet you 
nice to meet you 

Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. quit

使用标志

  • 要求很多条件都满足才继续运行的程序中,可定义一个变量,用于判断整个程序是否处于活动状态。这个变量被称为 标志。
  • 这个变量被称为 标志 ,充当了程序的交通信号灯。你可让程序在标志为 True 时继续运行,并在任何事件导致标志的值为 False 时让程序停止运行
prompt = "\nTell me somthing, 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)
Tell me somthing, and I will repeat it back to you: 
Enter 'quit' to end the program.hi
hi

Tell me somthing, and I will repeat it back to you: 
Enter 'quit' to end the program.quit

使用break退出循环

  • 要立即退出 while 循环,不再运行循环中余下的代码,也不管条件测试的结果如何,可使用 break 语句
  • break 语句用于控制程序流程,可使用它来控制哪些代码行将执行,哪些代码行不执行
  • 在任何 Python 循环中都可使用 break 语句
prompt = "\nTell me somthing, 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':
        break
    else:
        print(message)
Tell me somthing, and I will repeat it back to you: 
Enter 'quit' to end the program.hi
hi

Tell me somthing, and I will repeat it back to you: 
Enter 'quit' to end the program.quit

在循环中使用continue

  • 要返回到循环开头,并根据条件测试结果决定是否继续执行循环
current_number = 0
while current_number < 10:
    current_number += 1
    if current_number % 2 == 0:
        continue
    print(current_number)
1
3
5
7
9

使用while循环来处理列表和字典

  • 要在遍历列表的同时对列表进行修改,可使用 while 循环
  • 通过将 while 循环同列表和字典结合起来使用,可收集、存储并组织大量输入,供以后查看和显示

在列表之间移动元素

  • 从一个列表中元素移动到另一个列表中
#  首先,创建一个待验证用户列表
# 和一个用于存储已验证用户的空列表
unconfirmed_users = ['alice','brian','candace']
confirmed_users = []
#  验证每个用户,直到没有未验证用户为止
# 将每个经过验证的列表都移到已验证用户列表中
while unconfirmed_users:
    current_user = unconfirmed_users.pop()
    print("已验证 " + current_user.title())
    confirmed_users.append(current_user)
print("\n显示所有已验证用户")
for confirmed_user in confirmed_users:
    print(confirmed_user.title())
已验证 Candace
已验证 Brian
已验证 Alice

显示所有已验证用户
Candace
Brian
Alice

删除包含特定值的所有列表元素

  • 使用while循环删除特定元素
pets = ['dog','cat','dog','goldfish','cat','rabbit','cat']
print(pets)
while 'cat' in pets:
    pets.remove('cat')
print(pets)
['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
['dog', 'dog', 'goldfish', 'rabbit']

使用用户输入来填充字典

  • 使用while循环提示用户输入任意数量的信息
responses = {}
#  设置一个标志,指出调查是否继续
polling_active = True
while polling_active:
#  提示输入被调查者的名字和回答
    name = input("\nWhat is your name? ")
    response = input("Which mountain would you like to climb someday? ")
#  将答卷存储在字典中,键和值
    responses[name] = response
#  看看是否还有人要参与调查
    repeat = input("Would you like to let another person respond? (yes/ no) ")
    if repeat == 'no':
        polling_active = False
#  调查结束,显示结果
print("\n--- Poll Results ---")
for name, response in responses.items():
    print(name.title() + " would like to climb " + response.title() + ".")
What is your name? yegeli
Which mountain would you like to climb someday? tanshang
Would you like to let another person respond? (yes/ no) yes

What is your name? ww
Which mountain would you like to climb someday? furongshan
Would you like to let another person respond? (yes/ no) no

--- Poll Results ---
Yegeli would like to climb Tanshang.
Ww would like to climb Furongshan.

练习

# 1.熟食店
# 创建一个名为 sandwich_orders 的列表,在其中包含各种三明治的名字;再创建一个名为 finished_sandwiches 的空列表。遍历列
# 表 sandwich_orders ,对于其中的每种三明治,都打印一条消息,如 I made your tuna sandwich ,并将其移到列表 finished_sandwiches 。
# 所有三明治都制作好后,打印一条消息,将这些三明治列出来。
sandwich_orders = ['name1','name2','name3']
finished_sandwiches = []
while sandwich_orders:
    sandwich = sandwich_orders.pop()
    print("I made your tuna " + sandwich.title() + " .")
    finished_sandwiches.append(sandwich)
print("sandwiches is finished! ")
for finish_sandwich in finished_sandwiches:
    print(finish_sandwich)
I made your tuna Name3 .
I made your tuna Name2 .
I made your tuna Name1 .
sandwiches is finished! 
name3
name2
name1
# 2.五香烟熏牛肉pastrami卖完了
# 使用为完成练习 1而创建的列表 sandwich_orders ,并确保 'pastrami' 在其中至少出现
# 了三次。在程序开头附近添加这样的代码:打印一条消息,指出熟食店的五香烟熏牛肉卖完了;
# 再使用一个 while 循环将列表 sandwich_orders 中的 'pastrami' 都删除。确认最终的列表
# finished_sandwiches 中不包含 'pastrami' 
sandwich_orders = ['name1','pastrami','name2','pastrami','name3','pastrami']
finished_sandwiches = []
print("The pastrami is over! ")
while 'pastrami' in sandwich_orders:
    sandwich_orders.remove('pastrami')
print(sandwich_orders)
while sandwich_orders:
    sandwich = sandwich_orders.pop()
    print("I made your " + sandwich.title() + " .")
    finished_sandwiches.append(sandwich)
print("sandwiches is finished! ")
for finish_sandwich in finished_sandwiches:
    print(finish_sandwich)
The pastrami is over! 
['name1', 'name2', 'name3']
I made your Name3 .
I made your Name2 .
I made your Name1 .
sandwiches is finished! 
name3
name2
name1
# 3.梦想的度假胜地:
# 编写一个程序,调查用户梦想的度假胜地。使用类似于 “If you could visit one place in the world, where would you go?” 
# 的提示,并编写一个打印调查结果的代码块。
holidays = {}
active = True
while active:
    name = input("请输入您的姓名: ")
    address = input("请输入您想去的地方:")
    holidays[name] = address
    other_people = input("是否要继续输入(是/否):")
    print("\n")
    if other_people == "否":
        active = False
    else:
        continue
print("-----The Result----")
for name,address in holidays.items():
    print(name + " ,想去" + address +"度假!")
请输入您的姓名: 野哥李
请输入您想去的地方:天安门
是否要继续输入(是/否)是


请输入您的姓名: 小姐姐
请输入您想去的地方:大连
是否要继续输入(是/否)否


-----The Result----
野哥李 ,想去天安门度假!
小姐姐 ,想去大连度假!
posted @ 2019-09-25 00:01  野哥李  阅读(4)  评论(0编辑  收藏  举报  来源