Python—while循环

本文详细介绍了while循环在Python编程中的应用,包括基本用法、用户输入控制、标志在程序中的作用、break和continue语句,以及如何结合列表和字典进行操作,如移动元素、删除特定值和收集用户输入。
摘要由CSDN通过智能技术生成

1. while循环

for 循环用于针对集合中的每个元素都一个代码块,而while 循环不断地运行,直到指定的条件不满足为止。

1.1 使用while循环

你可以使用 while 循环来数数,例如,下面的 while 循环从 1 数到 5
current_number = 1
while current_number <= 5:
    print(current_number)
    current_number += 1

结果:

1
2
3
4
5

1.2 让用户选择何时退出

可使用 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)
    print(message)

结果:

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

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

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

1.3 使用标志

在要求很多条件都满足才继续运行的程序中,可定义一个变量,用于判断整个程序是否处于活动状态。这个变量被称为标志 ,充当了程序的交通信号灯。你可让程序在标志 为True 时继续运行,并在任何事件导致标志的值为 False 时让程序停止运行。这样,在 while 语句中就只需检查一个条件 —— 标志的当前值是否为 True ,并将所有测试(是否发生了应将标志设置为False 的事件)都放在其他地方,从而让程序变得更为整洁。
用一个例子就能明白什么是标志:
prompt = "\nTell me something, 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)

1.4 使用break退出循环

要立即退出 while 循环,不再运行循环中余下的代码,也不管条件测试的结果如何,可使用 break 语句。例如,来看一个让用户指出他到过哪些地方的程序。在这个程序中,我们可以在用户输入 'quit' 后使用 break 语句立即退出 while 循环:
prompt = "\nPlease enter the name of a city you have visited:"
prompt += "\n(Enter 'quit' when you are finished.) "
while True:
    city = input(prompt)
    if city == 'quit':
        break
    else:
        print("I'd love to go to " + city.title() + "!")

1.5 在循环中使用continue

要返回到循环开头,并根据条件测试结果决定是否继续执行循环,可使用 continue 语句,它不像 break 语句那样不再执行余下的代码并退出整个循环。
例如,来看一个从 1 数到10 ,但只打印其中奇数的循环:
current_number = 0
while current_number < 10: 
    current_number += 1
    if current_number % 2 == 0:
        continue
    print(current_number)

结果:

1
3
5
7
9

2. 用while循环处理列表和字典

for 循环 是一种 遍历列表的有效方式 ,但 在for 循环中不应修改列表 ,否则将导致 Python 难以跟踪其中的元素。要在遍历列表的同时 对其进行修改,可使用while 循环 。通过将while 循环同列表和字典结合起来使用,可收集、存储并组织大量输入,供以后查看和显示。

2.1 在列表之间移动元素

# 首先,创建一个待验证用户列表
# 和一个用于存储已验证用户的空列表
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("\nThe following users have been confirmed:")
for confirmed_user in confirmed_users:
    print(confirmed_user.title())

ps:函数pop() 以每次一个的方式从列表unconfirmed_users 末尾删除未验证的用户。

结果:

Verifying user: Candace
Verifying user: Brian
Verifying user: Alice
The following users have been confirmed:
Candace
Brian
Alice

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

我们使用函数 remove() 来删除列表中的特定值。在while循环中使用函数remove()即可删除包含特定值的所有列表元素。
示例:
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']

2.3 使用用户输入来填充字典

可使用 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 + " would like to climb " + response + ".")

结果:

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

What is your name? Lynn
Which mountain would you like to climb someday? Devil's Thumb
Would you like to let another person respond? (yes/ no) no

--- Poll Results ---
Lynn would like to climb Devil's Thumb.
Eric would like to climb Denali.

  • 8
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值