python学习笔记(八)while循环

霸气de小男生 提交于 2020-01-31 03:36:19

python学习笔记(八)while循环

1、while循环初见
在之前的博客中我们曾经学习过for循环,这里为大家介绍另一个循环——while。
while的语法很简单,我们结合它的英文释义“当···的时候”可知,只要满足while后面跟着的条件语句,那么它的循环体就会一直执行。由此可见,for循环与while循环最主要的用法区别就是:
如果我们知道循环次数,一般会选择for循环,但如果要求只要满足条件,就得执行操作,就选择while循环。

age = 16
while (age < 18):
	print("You are " + str(age) + " years old.")
	print("Therefore, you are still a child, now.")
	age += 1
print("You are " + str(age) + " years old.")
print("Therefore, you have become an adult!")

运行结果为:

You are 16 years old.
Therefore, you are still a child, now.
You are 17 years old.
Therefore, you are still a child, now.
You are 18 years old.

可见,while循环的一般格式为:

while conditional_test:
	do something

因此,while循环根本不关心循环会执行多少次(当然如果用户想知道,可以在循环体里放置一个动态更新的变量),只要conditional_test为True,则执行一次do something,再继续判断。

2、while循环的优势
我个人认为while循环最大的优点在于:它可以将程序进程交给用户,我们只需要在conditional_test中设置一个用户可以控制的出口,那么用户就可以在程序外部控制while循环。看一个简单的例子:

message = "Please tell me something, then I'll repeat it back to you: "
message += "\nIf you are unwilling to play, just tell me 'quit'.\n"
get = ''
while (get != 'quit'):
	get = input(message)
	if(get != 'quit'):
		print(get)

运行结果为:

Please tell me something, then I'll repeat it back to you: 
If you are unwilling to play, just tell me 'quit'.
Hello!
Hello!

Please tell me something, then I'll repeat it back to you: 
If you are unwilling to play, just tell me 'quit'.
My name is Good!
My name is Good!

Please tell me something, then I'll repeat it back to you: 
If you are unwilling to play, just tell me 'quit'.
quit

3、while循环的改进

有时候有多个条件制约着while循环的进程,那么我们可以设置一个标志变量(如flag),用它来显示while循环是否在执行中。这样不仅方便我们控制它,因为一旦有条件改变,可以直接修改标志变量的值;而且一旦while循环意外停止,这样做便于我们进行调试。

4、continue与break
continue关键字
忽略循环中剩余的代码,直接返回循环开头,并根据条件测试结果决定是否继续执行循环。
例子:

#打印出100以内3的所有倍数
number = 0
while (number <= 100):
	number += 1
	if (number%3 != 0):
		continue
	else:
		print(number)

break关键字
立即退出循环,不再运行循环中剩余的代码。
例子:

number = 0
while True:
	number += 1
	if (number>100):
		break
	if (number%3 == 0):
		print(number)

和上面那个例子功能相同,但实际上用处不同,break关键字的存在让我们可以写出while True这样的代码(死循环),因为我们完全可以在程序的内部利用break实现出口。

5、while较之于for的优势
我在之前曾经提到过for循环可以用来遍历,但是它不能在遍历的同时进行值的修改,因为这很有可能会导致无法跟踪全部的元素,但是while循环没有这样的问题,下面是while循环针对列表和字典的应用。

A 元素标记

languages_to_learn = ['python', 'c', 'java', 'ruby']
languages_learned = []
print("languages_to_learn:")
print(languages_to_learn)
print("\nlanguages_learned:")
print(languages_learned)
print()
while languages_to_learn:
	language_learning = languages_to_learn.pop()
	print("I am learning " + language_learning + ".")
	languages_learned.append(language_learning)
print("\nlanguages_to_learn:")
print(languages_to_learn)
print("\nlanguages_learned:")
print(languages_learned)

运行结果为:

languages_to_learn:
['python', 'c', 'java', 'ruby']

languages_learned:
[]

I am learning ruby.
I am learning java.
I am learning c.
I am learning python.

languages_to_learn:
[]

languages_learned:
['ruby', 'java', 'c', 'python']

这个操作相信大家很熟悉,很多算法都会用到这样的标记思想,用来防止重复运算。

B 列表元素删除
大家应该还记得我之前提到的 .remove() 函数只能删除列表中指定元素值第一次的出现,如果我们想把列表中指定的元素值全部删除,可以用while。看例子:

languages_0 = ['python', 'c', 'java', 'ruby', 'python']
languages_0.remove('python')
print(languages_0)
languages_1 = ['python', 'c', 'java', 'ruby', 'python']
while ('python' in languages_1):
	languages_1.remove('python')
print(languages_1)

运行结果为:

['c', 'java', 'ruby', 'python']
['c', 'java', 'ruby']

C 字典信息更新
这里我看到过一个很有趣的小例子,大家可以仔细体会一下while循环的作用。

favorite_languages = {}

#设置一个标志,记录循环状态
flag = True

while flag:
	name = input("\nWhat's your name?\n")
	language = input("What's your favorite language?\n")

	favorite_languages[name] = language

	repeat = input("Go on?(y/n)")
	if (repeat == 'n'):
		flag = False

print("\n----Results are as followings.----\n")
for name, language in favorite_languages.items():
	print(name + " likes " + language + " best!")
print("Over!")

运行结果为:
在这里插入图片描述

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!