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)

测试记录:

扫描二维码关注公众号,回复: 12915466 查看本文章
>>> 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编程:从入门到实践

猜你喜欢

转载自blog.csdn.net/u010520724/article/details/115206954