目录
2. 循环中的 break、continue 语句及 else 子句
1. 常见的流程控制语句
1.1 while语句
- 格式
while 条件:
条件满足时,做的事情1
条件满足时,做的事情2
条件满足时,做的事情3
...(省略)...
- demo
# -*- coding: utf-8 -*-
# @Time : 2021/2/1
# @Author : 大海
i = 0
while i < 5:
print("当前是第%d次执行循环" % (i + 1))
print("i=%d" % i)
i += 1
# 计算1~100的累积和(包含1和100)
j = 1
s = 0
while j <= 100:
s = s + j
j += 1
print("1~100的累积和为:%d" % s)
# 斐波那契数列
a, b = 0, 1
while a < 10:
print(a)
a, b = b, a + b
1.2 if语句
- 格式
if 要判断的条件:
条件成立时,要做的事情
- demo
# -*- coding: utf-8 -*-
# @Time : 2021/2/1
# @Author : 大海
# if 语句
age = 27
print("------if判断开始------")
if age >= 18:
print("我已经成年了")
print("------if判断结束------")
1.3 elif语句
- 格式
if xxx1:
事情1
elif xxx2:
事情2
elif xxx3:
事情3
- demo
# -*- coding: utf-8 -*-
# @Time : 2021/2/1
# @Author : 大海
# elif语句
score = 77
if 90 <= score <= 100:
print('本次考试,等级为A')
elif 80 <= score < 90:
print('本次考试,等级为B')
elif 70 <= score < 80:
print('本次考试,等级为C')
elif 60 <= score < 70:
print('本次考试,等级为D')
elif 0 <= score < 60:
print('本次考试,等级为E')
1.4 for语句
- 格式
for 临时变量 in 列表或者字符串等可迭代对象:
循环满足条件时执行的代码
- demo
# -*- coding: utf-8 -*-
# @Time : 2021/2/1
# @Author : 大海
# for 循环遍历字符串
info = '我是测试小白'
for x in info:
print(x)
# for 循环遍历列表
words = ['cat', 'window', 'defenestrate']
for w in words:
print(w, len(w))
# for 循环遍历字典
info_dict = {'name': '小白', 'sex': '男', 'age': 27, 'base': '大连'}
for k, v in info_dict.items():
print(k, v)
1.5 range()函数
- 作用:常用于遍历数字序列
# -*- coding: utf-8 -*-
# @Time : 2021/2/1
# @Author : 大海
# 生成的序列不包含给定的终止数值
for i in range(10):
print(i)
# 指定起始值
for j in range(3, 10):
print(j)
# 指定步长
for k in range(0, 10, 2):
print(k)
# 其他
res = sum(range(4)) # 0 + 1 + 2 + 3
print(res) # 6
print(list(range(4))) # [0, 1, 2, 3]
2. 循环中的 break
、continue
语句及 else
子句
2.1 break语句
# -*- coding: utf-8 -*-
# @Time : 2021/2/1
# @Author : 大海
# 跳出for循环
for n in range(2, 10):
if n % 2 == 0:
print(n)
break
# 跳出while循环
i = 0
while True:
i += 1
if i > 5:
print(i)
break
2.2 containue语句
- 作用:继续执行循环的下一次迭代
# -*- coding: utf-8 -*-
# @Time : 2021/2/1
# @Author : 大海
for num in range(2, 10):
if num % 2 == 0:
print("Found an even number", num)
continue
print("Found an odd number", num)
2.3 else语句
- 作用:可迭代对象中的元素全部循环完毕时,或
while
循环的条件为假时,执行该子句
# -*- coding: utf-8 -*-
# @Time : 2021/2/1
# @Author : 大海
# if 语句中使用else 所有条件都不满足时,执行else语句
x = 66
if x < 0:
x = 0
print('Negative changed to zero')
elif x == 0:
print('Zero')
elif x == 1:
print('Single')
else:
print('More')
# for循环 语句中使用else 循环中没有执行break,或可迭代对象中的元素全部循环完毕时执行else语句
for n in range(2, 10):
for x in range(2, n):
if n % x == 0:
print(n, 'equals', x, '*', n // x)
break
else:
print(n, 'is a prime number')
# while 语句中使用else 循环中没有执行break,或可迭代对象中的元素全部循环完毕时执行else语句
i = 0
while i < 5:
i = i + 10
print('----')
print(i)
else:
print("==while循环过程中,如果没有执行break退出,则执行本语句==")