你可以使用while循环不断的运行代码块,直到指定的条件不满足为止
简单的while循环
current_point = 18 #将current_point初始值设定为18,因此指定从18开始
while current_point <= 22: # 在这个while循环中,只要current_point的值小于或等于22,就接着运行这个循环。由于18小于22,因此执行下面的代码块,打印出18,并将current_point值加,变为19,由于大于22,将继续执行循环,一旦current_point大于22,循环将终止
print(current_point) #打印current_point的值
current_point += 1 #current_point值加1
#执行结果为:
18
19
20
21
22
让用户选择何时退出循环
message = "please tell me a number that you like, and I will repeat it back to you: "
message += "\nplease write 'quit' if you would like to end the program." # 我们定义了一条提示消息,告诉用户要么输入一个数据,要么按quit退出循环
number = "" # 我们创建了一个变量number,初始值为空字符串,但符合while循环的条件的,不同于quit,python将进入循环
while number != "quit":
number = input(message) # 等待用户输入,无论用户输入什么,都将存储在变量number中,并打印出来,主要用户输入的不是单词quit,循环将会一直持续下去,直到用户输入quit,循环就结束。
if number != "quit": 当用户的输入不是quit时,才打印用户输入的消息,若是quit就直接跳出循环
print(number)
#输出结果为:
please tell me a number that you like, and I will repeat it back to you:
please write 'quit' if you would like to end the program. **8** #当用户输入8,程序就打印8
8
please tell me a number that you like, and I will repeat it back to you:
please write 'quit' if you would like to end the program.**quit** #当用户输入quit, 循环就直接跳出循环
Process finished with exit code 0
使用标志如active = False退出循环
在要求很多条件满足才运行的程序中,可定义一个变量,用于判断整个程序是否处于活动状态,这个变量称为标志。你可让程序在标志为True时运行,并在任何事件导致标志为False时结束循环。
message = "please tell me a number that you like, and I will repeat it back to you: "
message += "\nplease write 'quit' if you would like to end the program."
active = True # 变量初始值设为True,让程序最初处于活动状态
while active:
number = input(message)
if number == "quit":
active = False # 如果用户输入的是quit,active就变成False,这将导致循环不再继续执行
else:
print(number)
# 运行结果如下:
please tell me a number that you like, and I will repeat it back to you:
please write 'quit' if you would like to end the program.**8**
8
please tell me a number that you like, and I will repeat it back to you:
please write 'quit' if you would like to end the program.**quit**
Process finished with exit code 0
使用break退出循环
要立即退出循环,不再运行循环中余下的代码,也不管条件测试的结果如何,可使用break语句
message = "please tell me a city that you have been, and I will repeat it back to you: "
message += "\nplease write 'quit' if you would like to end the program."
while True: # 以 while True 开头的循环将不断运行,直到遇到break语句。
city = input(message)
if city == "quit":
break # 如果用户输入的是quit, 程序就终止
else:
print(city)
# 运行的结果:
please tell me a city that you have been, and I will repeat it back to you:
please write 'quit' if you would like to end the program.**canton** # 这里的canton是用户输入的信息
canton # 这里的canton是程序返回的信息
please tell me a city that you have been, and I will repeat it back to you:
please write 'quit' if you would like to end the program.**quit** # quit 是用户输入的,因此程序将终止
Process finished with exit code 0
在循环中用continue
要返回到循环的开头,并根据条件测试的结果决定是否继续执行循环,可使用continue语句,来看一个1到12的数,但其中只打印奇数的循环
number = 0
while number <= 12:
number += 1
if number % 2 == 0:
continue # 当一个数能够被2整除,说明是偶数,就执行continue语句,跳过下面的代码块,重新开始新的循环
else:
print(number)
# 输出结果为:
1
3
5
7
9
11
使用while循环来处理列表和字典
- 在列表之间移动元素
unfinished_tasks = ["reading", "exercise", "cooking", "learning_python"]
finished_tasks = []
while unfinished_tasks: # 此处的while循环将不断运行,直到列表unfinished_tasks为空时,循环才停止
current_task = unfinished_tasks.pop() # 以每次一个的方式从列表unifinished_tasks的末尾删除未完成的任务,并存储在新的变量current_task中,由于learning_python位于列表末端,因此其名字将首先被删除
finished_tasks.append(current_task) # 从unfinished_tasks列表末尾删除的元素将每次一个的方式加入到列表finished_tasks中
print("The tasks that you have finished are following: ")
for finished_task in finished_tasks: # 遍历列表finished_tasks中的每个元素,并打印出来
print(finished_task)
print(unfinished_tasks) #打印列表unfinished_tasks的元素,由于上面的while循环每次从列表末尾删除一个元素,直到这个列表为空时才结束循环,因此,当循环结束时,此列表为空
# 输出结果为:
The tasks that you have finished are following:
learning_python
cooking
exercise
reading
[]
- 删除包含特定值的所有列表元素
假设你有一个未完成任务的列表,其中包括多个值为"reading"的元素,由于你最近很忙,没有多余时间来完成reading这个任务,因此打算从列表中把所有的reading元素删除,可不断运行一个while循环,直到列表中不再包含值”reading“,循环才结束,如下所示:
unfinished_tasks = ["reading", "exercise", "reading", "cooking", "learning_python", "reading"]
while "reading" in unfinished_tasks: # 直到列表unifinished_task中没有'reading'这个元素,循环才结束
unfinished_tasks.remove("reading") # 以每次一个的方式从列表unfinished_tasks中删除reading这个元素
print(unfinished_tasks)
# 输出结果为:
['exercise', 'cooking', 'learning_python']
- 使用用户输入来填充字典
responses = {} # 创建一个空的字典
active = True # 设置一个标志active的初始状态为True,将执行下面的循环,直到碰到active = False,循环才结束
while active:
name = input("What is your name? ") # 提示用户输入名字
response = input("What is your most favorite sport? ") # 提示用户输入最喜爱的运动
responses[name] = response # 将用户输入的名字作为键和用户输入的最喜爱的运动作为键相对应的值存储在字典responses中
repeat = input("Would you like to let another person respond? (yes/ no)") # 看看是否还要人要参与调查
if repeat == "no": # 如果用户的输入为no
active = False # active = False,循环结束
for name, response in responses.items(): # 遍历字典的键与值
print("The favorite sport of " + name.title() + " is " + response.title() + ".")
# 输出结果为:
What is your name? **lee**
What is your most favorite sport? **jogging**
Would you like to let another person respond? (yes/ no)**yes**
What is your name? **chen**
What is your most favorite sport? **jogging**
Would you like to let another person respond? (yes/ no)**no**
The favorite sport of Lee is Jogging.
The favorite sport of Chen is Jogging.
参考的书籍:
Python 编程从入门到实践 Eric Mattes 著,袁国忠 译