一、循环的作用:
让代码更高效的重复执⾏。
二、循环的类型:
三、退出循环的方法:
满⾜⼀定条件退出循环的两种不同⽅式
四、实际操练
1、 while循环
- 单循环
语法:
while 条件:
条件成⽴重复执⾏的代码1
条件成⽴重复执⾏的代码2
......
利用while循环计算1-100的累加和
'''
while循环实例1:1-100累加。
步骤:
1、准备做累加运算的数据,增量为1
2、准备变量保存运算的结果
3、循环加法运算
4、打印结果
'''
# 准备数据
i = 1
# 结果变量
result = 0
# 循环
while i <= 100:
# 前面累加的结果加上最新的数据,每计算一次,更新一次result的结果
result += i
i += 1
# 打印结果
print(result)
out:
5050
利用while循环计算1-100偶数累加和
'''
while循环实例2:1-100偶数累加
步骤:
1、准备做累加运算的数据,确认初始值,增量为1
2、准备变量保存运算的结果
3、判断进行累加的加数是否为偶数,循环进行加法运算
(与2进行取余,余数为0,则为偶数)
4、打印结果
'''
# 准备数据
i = 1
# 结果变量
result = 0
# 循环
while i <= 100:
# 判断是否为偶数
if i % 2 == 0:
# 前面累加的结果加上最新的数据,每计算一次,更新一次result的结果
result += i
# 无论是否为偶数,i都会自增1
i += 1
# 打印结果
print(result)
out:
2550
- while循环嵌套
语法:
while 条件1:
条件1成⽴执⾏的代码
......
while 条件2:
条件2成⽴执⾏的代码
......
利用while循环嵌套,计算1-100偶数累加和
i = 1
result = 0
while i <= 100:
while i % 2 == 0:
result += i
i += 1
i += 1
print(result)
- while…else… 与终止循环
"""
while与else搭配使用
1、语法
*****
while 条件“
重复执行代码1
...
else
代码
*****
2、else下方缩进的代码表示 循环正常结束后要执行的代码
3、如果使用break终止循环,则不会执行else下的代码;如果使用continue,循环正常结束,会执行else下的代码
"""
# break
i = 1
while i < 6:
# 一定要实现计数器的自增
if i == 3:
break
print(f'吃了{i}个苹果了')
i += 1
else:
print('吃饱了')
out:
# continue
i = 1
while i < 6:
if i == 3:
# 一定要实现计数器的自增
i += 1
continue
print(f'吃了{i}个苹果了')
i += 1
else:
print('吃饱了')
out:
由上可知:使用break退出循环,循环非正常退出;使用continue退出循环,循环依旧会正常结束。
2、 for循环
3.1、for
语法:
for 临时变量 in 序列:
重复执⾏的代码1
重复执⾏的代码2
......
str1 = 'children'
for i in str1:
print(i)
out:
c
h
i
l
d
r
e
n
3.2、for…else
"""
1、for循环语法
for 临时变量 in 序列:
重复执行的代码块
...
else:
代码块
2、else下方缩进的代码表示 循环正常结束后要执行的代码
3、如果使用break终止循环,则不会执行else下的代码;如果使用continue,循环正常结束,会执行else下的代码
"""
str1 = 'children'
for i in str1:
# 当读取到d字母,则退出循环
if i == 'd':
break
print(f'当前读取的字符是{i}')
else:
print('读取完毕')
out:
break终止循环,else后的代码未执行
当前读取的字符是c
当前读取的字符是h
当前读取的字符是i
当前读取的字符是l
continue:
list1 = [1, 2, 3, 4]
for i in list1:
if i == 3:
continue
print(f'当前读取的字符是{i}')
else:
print('读取完毕')
out:
continue退出循环,else后的代码得到了执行
当前读取的字符是1
当前读取的字符是2
当前读取的字符是4
读取完毕
3、 退出循环
- break
'''
break实例:
吃5个苹果,吃完第三个饱了,不继续吃了
'''
i = 1
while i <= 5:
if i > 3:
print('吃饱了,不想吃了')
break
print(f'吃了{i}个苹果了')
i += 1
out:
- continue
'''
continue实例:
吃5个苹果,吃到第三个,发现第三个有虫子,不吃了,继续吃下一个
'''
i = 1
while i <= 5:
if i == 3:
print('有虫子。。。。扔了')
# 跳出本次循环,继续下一轮循环前先做自增,不然会出现死循环
i += 1
continue
print(f'吃了{i}个苹果了')
i += 1
out: