Python_while循环

/ Python / 没有评论 / 1326浏览

while上场了

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

敲下你的第一个while循环

[root@pa1 lijinghua]#python while.py
1
2
3
4
5
[root@pa1 lijinghua]#cat while.py
#!/usr/local/python
current_number=1              #定义初始值
while current_number <=5:     #定义一个最高值
	print(current_number)
	current_number +=1    #每次加1

让用户选择何时退出

示范:

[root@pa1 lijinghua]#python while_2.py

Tell me something, and i will repeat it back to you:
Enter 'quit' to end the program:quit
quit
[root@pa1 lijinghua]#cat while_2.py
#!/usr/local/python
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)

以上代码虽然能解释,但是不太完美.在用户不是输入 'quit'的情况下,也会打印 输入的东西,

[root@pa1 lijinghua]#python while_2.py

Tell me something, and i will repeat it back to you:
Enter 'quit' to end the program:www

Tell me something, and i will repeat it back to you:
Enter 'quit' to end the program:quit
quit
[root@pa1 lijinghua]#cat while_2.py
#!/usr/local/python
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)
	if message == 'quit':
		print(message)

使用信号标志

在要求很多条件都满足才能运行的程序中,可定义一个变量,用于判断整个程序是否处于活动状态.这个变量被称为标志,充当了整个程序的交通信号灯. 你可让程序在标志为True时继续运行,并在任何事件导致标志的值为False时让程序停止运行.

示范

[root@pa1 lijinghua]#python while_3.py

Tell me something, and i will repeat it back to you:
Enter 'quit' to end the program:www
www

Tell me something, and i will repeat it back to you:
Enter 'quit' to end the program:quit
[root@pa1 lijinghua]#cat while_3.py
#!/usr/local/python
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':            #当输入的字符为'quit'时
		active = False           #'False'停止表示,不进行后面的打印
	else:
		print(message)           #如果不是'False'时,打印当前行

使用break退出循环

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

示范

[root@pa1 lijinghua]#python while_4.py

Tell me something, and i will repeat it back to you:
Enter 'quit' to end the program:yuncheng
I love to go to Yuncheng

Tell me something, and i will repeat it back to you:
Enter 'quit' to end the program:quit
[root@pa1 lijinghua]#cat while_4.py
#!/usr/local/python
prompt="\nTell me something, and i will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program:"
while True:                                #注意这里的True 'T'是大写
	city=input(prompt)
	if city == 'quit':
		break                      #如果条件符合泽打断
	else:
		print("I love to go to "+city.title())

在循环中使用continue

要返回到循环开头,并根据条件测试结果决定是否继续执行循环,可使用continue语句,它不像break语句那样不再执行余下的代码并退出整个循环

示范

[root@pa1 lijinghua]#python continue.py
1
3
5
7
9
[root@pa1 lijinghua]#cat   continue.py
#! /usr/local/python
number=0
while number < 10:
	number +=1
	if number % 2 ==0:      #求模运算若结果为0,则重新循环
		continue
	print(number)

避免无限循环

示范

[root@pa1 lijinghua]#python continue.py
0
0
0
0
0
0
0
~~~~~~~~~~~无限

[root@pa1 lijinghua]#cat  continue.py
#! /usr/local/python
number=0
while number < 10:
#	number +=1       #变量如果不会变化,可能陷入死循环
	print(number)

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

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

在列表之间移动元素

单词 unconfirmed = 未验证

示范

[root@pa1 lijinghua]#python list_move.py
Addind user:yuxi
Addind user:congcong
Addind user:jinghua

list of number :
yuxi
congcong
jinghua
[root@pa1 lijinghua]#cat list_move.py
#!/usr/local/python
unconfirmed_users=['jinghua','congcong','yuxi']
confirmed_users=[]
while unconfirmed_users:
	current_user=unconfirmed_users.pop()
	print("Addind user:"+current_user)
	confirmed_users.append(current_user)
print("\nlist of number :")
for authorized_user in confirmed_users:
	print(authorized_user)

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

之前在列表中删除一个特定的值,remove()可以解决,但是假若这个值出现了好多次,可以使用while循环来删除这个值

示范

[root@pa1 lijinghua]#python while_remove.py
['lili', 'congcong', 'yuxi', 'meihua', 'jinghua', 'yuxi', 'yuxi']
['lili', 'congcong', 'meihua', 'jinghua']
[root@pa1 lijinghua]#cat while_remove.py
#!/usr/local/python
names=['lili','congcong','yuxi','meihua','jinghua','yuxi','yuxi']
print(names)
while 'yuxi'in  names:          #这里要做个限制,只有在列表中发现'yuxi'时,才进行以下的操作
	names.remove('yuxi')
print(names)

使用用户输入的数据来填充字典

单词 responses=响应回应 repeat = 重复,副本 poll = 轮循

示范

[root@pa1 lijinghua]#python yonghu_zidian.py

what is  your name:lijinghua
Which mountain would you like to climb someday?qiumingshan
would you like to let another person respond? (yes/no)yes

what is  your name:yuxi
Which mountain would you like to climb someday?fushishan
would you like to let another person respond? (yes/no)no
--- Poll Results ---
lijinghua like climb qiumingshan.
yuxi like climb fushishan.
[root@pa1 lijinghua]#cat yonghu_zidian.py
#! /usr/local/python
# -*- coding: utf-8 -*-
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)")
	if repeat == 'no':
#回答若是no的话,信号则为False,循环停止
			polling_active=False
print("--- Poll Results ---")
for name,response in responses.items():
	print(name + " like climb " + response +"." )