Python系列8-Python循环结构while语句

一.while循环简介

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

1.1 使用while 循环

你可以使用while 循环来数数,例如,下面的while 循环从1数到5。

代码:

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

测试记录:

>>> current_number = 1
>>> while current_number <= 5:
...     print(current_number)
...     current_number = current_number + 1
...
1
2
3
4
5
>>>

在第1行,我们将current_number 设置为1,从而指定从1开始数。接下来的while 循环被设置成这样:只要current_number 小于或等于5,就接着运行这个循环。循环中的代码打印current_number 的值,再使用代码current_number = current_number + 1 将其值加1。
只要满足条件current_number <= 5 ,Python就接着运行这个循环。由于1小于5,因此Python打印1 ,并将current_number 加1,使其为2 ;由于2小于5,因此Python打
印2 ,并将current_number 加1 ,使其为3 ,以此类推。一旦current_number 大于5,循环将停止,整个程序也将到此结束:

1
2
3
4
5

你每天使用的程序很可能就包含while 循环。例如,游戏使用while 循环,确保在玩家想玩时不断运行,并在玩家想退出时停止运行。如果程序在用户没有让它停止时停止运
行,或者在用户要退出时还继续运行,那就太没有意思了;有鉴于此,while 循环很有用。

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)

测试记录:

>>> 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. no
no

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

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

1.3 使用标志

在前一个示例中,我们让程序在满足指定条件时就执行特定的任务。但在更复杂的程序中,很多不同的事件都会导致程序停止运行;在这种情况下,该怎么办呢?

例如,在游戏中,多种事件都可能导致游戏结束,如玩家一艘飞船都没有了或要保护的城市都被摧毁了。导致程序结束的事件有很多时,如果在一条while 语句中检查所有这些条件,将既复杂又困难。

在要求很多条件都满足才继续运行的程序中,可定义一个变量,用于判断整个程序是否处于活动状态。这个变量被称为标志 ,充当了程序的交通信号灯。你可让程序在标志为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)

测试记录:

>>> 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)
...

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

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

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

1.4 使用break 退出循环

要立即退出while 循环,不再运行循环中余下的代码,也不管条件测试的结果如何,可使用break 语句。break 语句用于控制程序流程,可使用它来控制哪些代码行将执行,哪些代码行不执行,从而让程序按你的要求执行你要执行的代码。

代码:

prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program. "

while True:
    message = input(prompt)
    if message == 'quit':
        break
    else:
        print(message)

测试记录:

>>> prompt = "\nTell me something, and I will repeat it back to you:"
>>> prompt += "\nEnter 'quit' to end the program. "
>>>
>>> while True:
...     message = input(prompt)
...     if message == 'quit':
...         break
...     else:
...         print(message)
...

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

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

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

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)

测试记录:

>>> 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 循环中使用列表和字典。

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

2.1 在列表之间移动元素

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

代码:

# 首先,创建一个待验证用户列表和一个已验证用户列表
unconfirmed_users = ['Ada','Bob','Cindy']
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())

测试记录:

python.exe C:/Users/Administrator/PycharmProjects/untitled2/test3.py
Verifying user:Cindy
Verifying user:Bob
Verifying user:Ada

The following users have been confirmed:
Cindy
Bob
Ada

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

假设你有一个宠物列表,其中包含多个值为'cat' 的元素。要删除所有这些元素,可不断运行一个while 循环,直到列表中不再包含值'cat' 。

如下所示,通过值删除,每次只能删除重复的cat中的一个,有多少个需要执行多少次,因为列表中'cat'数是不固定的,此时可以通过while循环来实现。

>>> pets = ['dog','cat','dog','goldfish','cat','rabbit','cat']
>>> pets.remove('cat')
>>> print(pets)
['dog', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
>>> pets.remove('cat')
>>> print(pets)
['dog', 'dog', 'goldfish', 'rabbit', 'cat']
>>>

代码:

pets = ['dog','cat','dog','goldfish','cat','rabbit','cat']
print(pets)

while 'cat' in pets:
    pets.remove('cat')

print(pets)

测试记录:

python.exe C:/Users/Administrator/PycharmProjects/untitled2/test3.py
['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
['dog', 'dog', 'goldfish', 'rabbit']

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

可使用while循环提示用户输入任意数量的信息。
下面我们来做一个数据库排名的字典,通过用户输入数据库及排名,然后将输入打印出来.

代码:

ranks = {}

# 设置一个标志,指出调查是否继续
polling_active = True

while polling_active:
    # 提示输入数据库的名称和排名
    database = input("\nPlease input your database:")
    rank = input("\nPlease input your database rank:")

    # 将排名存储在字典中
    ranks[database] = rank;

    # 看看是否还需要继续输入
    repeat = input("Would you like to input another database? (yes/ no) ")
    if repeat == 'no':
        polling_active = False

# 输入结束,显示结果
print("\n--- input Results ---")
for database, rank in ranks.items():
    print(database + " ranking is  " + rank + ".")

测试记录:

python.exe C:/Users/Administrator/PycharmProjects/untitled2/test3.py

Please input your database:Oracle

Please input your database rank:1
Would you like to input another database? (yes/ no) yes

Please input your database:MySQL

Please input your database rank:2
Would you like to input another database? (yes/ no) yes

Please input your database:PostgreSQL

Please input your database rank:3
Would you like to input another database? (yes/ no) no

--- input Results ---
Oracle ranking is  1.
MySQL ranking is  2.
PostgreSQL ranking is  3.

Process finished with exit code 0

参考:

1.Python编程:从入门到实践

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,830评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,992评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,875评论 0 331
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,837评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,734评论 5 360
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,091评论 1 277
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,550评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,217评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,368评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,298评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,350评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,027评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,623评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,706评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,940评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,349评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,936评论 2 341

推荐阅读更多精彩内容