第七章 while循环

while循环基本原理

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

使用while循环

current_number = 1
while current_number <= 5:
    print(current_number)
    current_number += 1

使用标志

在要求很多条件都满足才继续运行的程序中,可定义一个变量,用于判断整个程序是否处于活动状态,这个变量被称为标志。当标志为True时继续运行,在任何事件导致标志的值为False时让程序停止运行。例如在前面的例子中添加一个标志:

prompt = '\nTell me something, and I will repeat it back to you: '
 
prompt += "\nEnter 'Q' to end the program. "
 
active = True
 
while active:
 
    message = input(prompt)
 
    if message == 'Q' or message == 'q':
 
        active = False
 
    else:
 
        print(message)
'''
Tell me something, and I will repeat it back to you:
 
Enter 'Q' to end the program. hello
 
hello
 
 
 
Tell me something, and I will repeat it back to you:
 
Enter 'Q' to end the program. hi
 
hi
 
 
 
Tell me something, and I will repeat it back to you:
 
Enter 'Q' to end the program. Q
'''

首先初始化active为True,然后在while循环中,使用if判断用户输入(也就是message)是否是结束标志(此例中是‘Q’或‘q’),如果是结束标志,则将变量active设置为False,否则将message的值作为一个消息打印出来。

使用break退出循环

要立即退出while循环,不再运行循环中余下的代码,也不管条件测试的结果如何,可使用break。break语句用于控制程序流程。例如:

prompt = '\nTell me something, and I will repeat it back to you: '
 
prompt += "\nEnter 'Q' to end the program. "
 
while True:
 
    message = input(prompt)
 
    if message == 'Q' or message == 'q':
 
        break
 
    else:
 
        print(message)
'''
Tell me something, and I will repeat it back to you:
 
Enter 'Q' to end the program. hel
 
hello
 
 
 
Tell me something, and I will repeat it back to you:
 
Enter 'Q' to end the program. hi
 
hi
 
 
 
Tell me something, and I will repeat it back to you:
 
Enter 'Q' to end the program. Q
'''

在循环中使用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
    '''

首先将变量current_number初始化为0,由于它小于10,进入while循环。进入循环后,以步长为1的方式往上数,然后以if语句检查current_number,如果current_number与2的求模结果为0(也就是current_number是偶数),就执行continue语句,让python忽略余下的语句,并返回到循环的开头。如果current_number不能让2整除,就执行循环中余下的代码,也就是将这个数字打印出来。

避免无限循环

每个while循环都必须有停止运行的途径,这样才不会一直执行下去。

如果程序陷入无限循环,可按Ctrl+C,也可以关闭显示程序输出的终端窗口。

要避免编写无限循环,务必对每个while循环进行测试,确保它可以按预期那样结果。

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

到目前为止,我们每次都只处理一项用户信息:获取用户的输入,再将输入打印出来或者作出应答;循环再次运行时,我们获取另一个输入值并作出响应。然而,要记录大量用户和信息,需要在while循环中使用列表和字典。

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

在列表之间移动元素

假设有一个列表,其中包含新注册但未验证的网站用户;验证这些用户后,如何将他们移到另一个已验证用户列表中呢?一个办法是使用一个while循环,在验证用户的同时将其从未验证用户列表中提取出来,再将其加入到另一个已验证用户列表中,如下例:

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())
'''
Verifying user: Candace
 
Verifying user: Brian
 
Verifying user: Alice
 
 
 
The following users have been confirmed:
 
Candace
 
Brian
 
Alice
'''

首先创建一个待验证的用户列表unconfirmed_users和一个用来存储已验证的用户的空列表confirmed_users。然后使用循环,依次验证unconfirmed_users中的元素。在循环体中,每次取出unconfirmed_users结尾的用户,并删除列表中的结尾用户,为了模拟用户验证的过程,打印一条验证消息,然后将验证后的用户存储到confirmed_users中。最后打印已验证的用户列表。

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

假设有一个列表,其中包含多个值为‘cat’的元素。要删除所有这些元素,可以使用while循环,依次删除‘cat’元素,直到列表中不再包含‘cat’。例如:

pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbin', 'cat']
 
print(pets)
 
 
 
while 'cat' in pets:
 
    pets.remove('cat')
 
 
 
print(pets)
#['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbin', 'cat']
 
#['dog', 'dog', 'goldfish', 'rabbin']

使用用户输入来填充字典

可使用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)\n")
 
    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? Aria
 
Which mountain would you like to climb someday? Taishan Mountain
 
Would you like to let another person respond?(yes/no)
 
yes
 
 
 
What is your name? Tom
 
Which mountain would you like to climb someday? Huashan Mountain
 
Would you like to let another person respond?(yes/no)
 
no
 
 
 
 --- Poll Results ---
 
Aria would like to climb Taishan Mountain.
 
Tom would like to climb Huashan Mountain.
'''

首先定义一个空字典responses,并设置一个是否继续调查的标志(polling_active),只要此标志为True,则继续执行循环。

在循环中,提示用户输入用户名以及喜欢爬的山。将这些信息存在字典responses中,然后询问用户调查是否继续。如果用户输入yes,程序将再次开启循环;如果用户输入no,polling_active被设置为False,while循环结束。最后打印出调查结果。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值