Contents
2.3. While循环¶
while循环不同于for循环,while循环是只要条件满足,那么就会一直运行代码块,否则就运行else代码块,语法如下:
while <条件>:
<代码块>
else:
<如果条件不成立执行这里的代码块>
2.3.1. 1.代码示例¶
#!/usr/bin/env python
#-*- coding:utf8 -*-
'''
while 条件表达式:
循环体
不满足条件表达式时,自动跳出循环
'''
number = 500 #定义范围
start_nu = 0 #计数器
while start_nu <= number:
if start_nu%3 == 2 and start_nu%5 == 3 and start_nu%7 == 2:
print("答曰 这个数值是:{}".format(start_nu))
start_nu +=1
print("循环结束!!")
2.3.2. 2.while代码演示¶
myList = ['English', 'chiese', 'hujianli', "hujianli2", "hujianli3"]
while len(myList) > 0:
print("pop element out:", myList.pop()) # 出栈,list中一个个退出,退出完毕,循环结束
2.3.3. 3.遍历输出列表¶
#!/usr/bin/env python
#-*- coding:utf8 -*-
alst = [1,2,3,4,5]
total = len(alst)
i = 0
while i < total:
print("{} 的平方是{}".format(alst[i], alst[i]*alst[i]))
i = i +1
else:
print("循环结束 !!")
2.3.4. 4.实现一个人机交互¶
#!/usr/bin/env python
# -*- coding:utf8 -*-
# auther; 18793
# Date:2019/12/22 12:29
# filename: 验收人机对话流程控制.py
"""
1.如果输入‘hello’,进入主程序,开启人机对话服务
2.如果输入‘go away’或者是‘bye’退出程序
3.如果输入‘pardon’,重新等待用户输入
"""
init_str = ''
while ("bye" != init_str):
if init_str == '':
print("hello Password!")
init_str = input("请输入你的选择:")
if init_str.strip() == "hello":
print("How are you today?")
init_str = "start"
elif init_str.strip() == 'go away' or init_str.strip() == "bye":
print("sorry bye-bye")
break
elif init_str.strip() == "pardon":
init_str = ''
continue
else:
pass
if init_str == "start":
print("........init diaolog-server ...........")
print("........ one thing.....................")
print("........ two thing ....................")
print("...................................")
代码示例
#!/usr/bin/env python
# -*- coding:utf8 -*-
# auther; 18793
# Date:2020/3/22 14:06
# filename: while循环01.py
while True:
print("who are you ?")
name = input()
if name.strip() != "hujianli":
continue
print("Hello ,hujianli ,What is the password? (It is a fish.)")
password = input()
if password.strip() == "admin#123":
break
print("Access granted")
2.3.5. 5.return语句¶
#!/usr/bin/env python
#-*- coding:utf8 -*-
def test():
for i in range(10):
for j in range(10):
print("i的值是:%d,j的值是:%d" % (i, j))
if j == 1:
return
print("return的输出语句")
test()
i的值是:0,j的值是:0
return的输出语句
i的值是:0,j的值是:1
2.3.6. 6.循环控制语句¶
6.1 break¶
for item in range(10):
#当循环到3的时候退出整个循环
if item == 3:
break
print("Count is:{0}".format(item))
6.2 continue¶
for item in range(10):
#当循环到3的时候,退出当前循环,进入下一次循环
if item == 3:
continue
print("Count is :{0}".format(item))
6.3 中断嵌套循环的方式¶
def print_first_world(fp,prefix):
"""
找到文件里第一个指定单词的前缀并打印
:param fp: 可读文件对象
:param prefix: 需要寻找的单词前缀
:return:
"""
first_word = None
for line in fp:
for word in line.split():
if word.startswith(prefix):
first_word = word
# 此处跳出内层循环
break
# 内层循环结束,跳出外层循环
if first_word:
break
if first_word:
print(f'Found the first word startswith "{prefix}"" "{first_word}"')
else:
print(f'Word starts with "{prefix}" was not found.')
我们可以把print_first_word()里的“寻找单词”部分拆分为一个独立函数
改写优化后的代码如下:
def find_first_world(fp,prefix):
"""
找到文件里第一个指定单词的前缀并打印
:param fp: 可读文件对象
:param prefix: 需要寻找的单词前缀
:return:
"""
first_word = None
for line in fp:
for word in line.split():
if word.startswith(prefix):
return word
return None
def print_first_world2(fp,prefix):
first_word = find_first_world(fp,prefix)
if first_word:
print(f'Found the first word startswith "{prefix}"" "{first_word}"')
else:
print(f'Word starts with "{prefix}" was not found.')
6.4 while和for+else语句结构¶
i = 0
while i * i < 10:
i += 1
print("{0}*{0}={1}".format(i, i * 1))
else:
print("while Over!")
print("".center(10, "*"))
# 当for循环中条件满足break语句执行时,程序不会进入else语句,不会输出“for over”
for i in range(10):
if i == 3:
break
print("Count is :{0}".format(i))
else:
print("for over!")